BOJ2164

김현민·2021년 1월 20일
0

Algorithm

목록 보기
8/126
post-thumbnail

BOJ2164. 카드 2

문제

코드1 (리스트 자료구조)

#include <iostream>
#include <list>

using namespace std;

int main(int argc, char const *argv[])
{

    cin.tie(NULL);
    ios::sync_with_stdio(false);
    int n;
    cin >> n;

    list<int> lt;

    for (int i = 1; i <= n; i++)
    {

        lt.push_back(i);
    }

    while (lt.size() > 1)
    {
        lt.pop_front();
        lt.push_back(lt.front());
        lt.pop_front();
    }

    cout << lt.front() << '\n';
    return 0;
}

코드2 (큐 자료구조)

#include <iostream>
#include <queue>

using namespace std;

int main()
{
    cin.tie(NULL);
    ios::sync_with_stdio(false);

    int n;
    cin >> n;
    queue<int> q;
    for (int i = 1; i <= n; i++)
    {
        q.push(i);
    }
    while (q.size() > 1)
    {

        q.pop();
        q.push(q.front());
        q.pop();
    }

    cout << q.front() << '\n';

    return 0;
}
  • 맨 처음 제출했을 때는 , 메모리 초과 오류로 실패하였다.
  • 변수를 굳이 쓰지않고 push_back인자에 front를 바로 대입해서 해결.



처음 시도했던 코드

while (!lt.empty())
    {
        lt.pop_front();
        int temp = lt.front();
        if (lt.size() == 1)
        {

            cout << temp << endl;
            break;
        }
        lt.pop_front();
        lt.push_back(temp);
    }
profile
Jr. FE Dev

0개의 댓글