BOJ1620

김현민·2021년 2월 12일
0

Algorithm

목록 보기
23/126
post-thumbnail

BOJ 1620. 나는야 포켓몬 마스터 이다솜

문제

코드

#include <iostream>
#include <vector>
#include <string>
#include <sstream>

using namespace std;
int num, low, high;
string temp;
int main(int argc, char const *argv[])
{
    cin.tie(NULL);
    ios::sync_with_stdio(false);
    int n, m;
    cin >> n >> m;
    vector<pair<string, int> > v;
    vector<string> v1;
    for (int i = 1; i <= n; i++)
    {
        string pokemon;
        cin >> pokemon;
        v1.push_back(pokemon);
        v.push_back(make_pair(pokemon, i));
    }

    sort(v.begin(), v.end());

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

        cin >> temp;

        if (temp[0] >= '0' && temp[0] <= '9')
        {
            std::stringstream ssInt(temp);
            ssInt >> num;
            // num = stoi(temp);
            cout << v1[num - 1] << '\n';
        }
        else
        {
            low = 0;
            high = n - 1;
            while (low <= high)
            {

                int mid = (low + high) / 2;

                if (v[mid].first == temp)
                {
                    cout << v[mid].second << '\n';
                    break;
                }
                else if (v[mid].first < temp)
                {
                    low = mid + 1;
                }
                else
                {
                    high = mid - 1;
                }
            }
        }
    }
    return 0;
}

이분탐색 하기전에는 시간초과 에러가 발생하였다. N이 10만이므로

해결책으로 이분탐색으로 통해 값들을 찾아나갔다.

그리고 숫자만 입력되었을 경우에 대비해 v1벡터(string값만 들어있는)를 따로 만들어 바로 출력되게 하였다.

profile
Jr. FE Dev

0개의 댓글