- 난이도: 브론즈 1
- 알고리즘: 그리디 알고리즘
사과가 바구니의 바깥에 있으면 닿을 때까지 한칸씩 움직이면 된다. 근데 처음에 푼 코드는 좌표끼리 차이를 구해서 움직였는데 왜 틀린건지 잘 모르겠다.. (아래 코드)
틀린 이유를 찾았다. bucket.first를 대입하는 도중에 값이 바뀌어서 틀린 것이다. 저번 반복문 때도 i 잘못써서 틀렸는데 임시 변수 만들어서 저장해두는거 습관을 들여둬야겠다..
pair<int, int> bucket(1, m);
for (int i = 0; i < j; i++) {
int x;
cin >> x;
if (x < bucket.first) {
cnt += bucket.first - x;
bucket.first -= bucket.first - x;
bucket.second -= bucket.first - x;
}
else if (x > bucket.second) {
cnt += x - bucket.second;
bucket.first += x - bucket.second;
bucket.second += x - bucket.second;
}
}
위 코드를 보완해서 한 칸씩만 움직이게 해줬더니 맞았다.
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n, m;
cin >> n >> m;
int j;
cin >> j;
int cnt = 0;
int bucket[2] = { 1, m };
for (int i = 0; i < j; i++) {
int x;
cin >> x;
while (x < bucket[0] || x > bucket[1]) {
if (x > bucket[1]) {
bucket[0]++;
bucket[1]++;
cnt++;
}
else if (x < bucket[0]) {
bucket[0]--;
bucket[1]--;
cnt++;
}
}
}
cout << cnt;
}