[백준] 2828 사과 담기 게임
#include <iostream>
#include <algorithm>
using namespace std;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL); cout.tie(NULL);
int N, M, j;
cin >> N >> M >> j;
int left = 1;
int right = M;
int move = 0;
while (j--) {
int apple;
cin >> apple;
while ((left >= 1) && (right <= N)) {
if ((left <= apple) && (apple <= right)) break;
if (apple < left) {
left--;
right--;
}
else if (apple > right) {
left++;
right++;
}
move++;
}
}
cout << move;
return 0;
}
3년 전 코드
#include <stdio.h>
#pragma warning(disable:4996)
int main() {
int n, m;
scanf("%d %d", &n, &m);
int k;
scanf("%d", &k);
int left = 1; int right = m;
int sum = 0;
for (int i = 0; i < k; i++) {
int apple, move;
scanf("%d", &apple);
if (left <= apple && apple <= right) move = 0;
else if (apple < left) {
move = (left - apple);
left -= move;
right -= move;
}
else if (right < apple) {
move = (apple - right);
left += move;
right += move;
}
sum += move;
}
printf("%d", sum);
return 0;
}