[HackerRank] New Year Chaos

문제 링크 - https://www.hackerrank.com/challenges/new-year-chaos/problem?h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=arrays

보통 난이도의 배열 활용 문제


It's New Year's Day and everyone's in line for the Wonderland rollercoaster ride! There are a number of people queued up, and each person wears a sticker indicating their initial position in the queue. Initial positions increment by  from  at the front of the line to  at the back.
Any person in the queue can bribe the person directly in front of them to swap positions. If two people swap positions, they still wear the same sticker denoting their original places in line. One person can bribe at most two others. For example, if and  bribes , the queue will look like this: .
Fascinated by this chaotic queue, you decide you must know the minimum number of bribes that took place to get the queue into its current state!





void minimumBribes(vector<int> q) {
    for (int i = 0; i < q.size(); i++) {
        if (q[i] - i > 3) {
            cout << "Too chaotic" << endl;
            return;
        }
    }

    int answer = 0;
    while (true) {
        bool flag = false;
        int tmp;
        for (int i = 0; i < q.size() - 1; i++) {
            if (q[i] > q[i + 1]) {
                flag = true;
                //cout << q[i] << ", " << q[i+1]<<endl;
                tmp = q[i];
                q[i] = q[i + 1];
                q[i + 1] = tmp;
                answer++;
            }
        }

        if (!flag) break;
    }

    cout << answer << endl;

}

댓글

이 블로그의 인기 게시물

Unity - Dialogue 시스템을 구현할 때 유용한 무료 에셋

Unity - 메타 파일

Unity - 라이브러리 폴더