[PS 백준 - 3.3] 2828번: 사과 담기 게임

PongkiJoa·2021년 6월 30일
0

PS Diary - 백준

목록 보기
28/54
post-thumbnail

문제 정보

백준 2828번 - 바로가기

  • 난이도: 브론즈 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;
}
profile
컴공 20학번

0개의 댓글

관련 채용 정보