Programming/Baekjoon

[백준/c++] 1181번 : 단어 정렬

만나쓰 2020. 9. 9. 01:58

www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

첫째 줄에 단어의 개수 N이 주어진다. (1≤N≤20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.

www.acmicpc.net

#include<iostream>
#include<vector>
using namespace std;

int main() {
    int n, index;
    cin >> n;
    vector<string> str(n), res;
    for (int i = 0; i < n; i++) {   // n개의 string 입력받기
        cin >> str[i];
    }

    // 벡터 안에 string 길이 순서대로 정렬  
    while (!str.empty()) {
        index = 0;
        str[index] = str[0];

        for (int i = 1; i < str.size(); i++) {  // str 중 길이 최소인 index 찾기!
            if (str[index].length() > str[i].length() || ( str[index].length() == str[i].length() && str[index] > str[i])) {
                index = i;
            }
            else if (str[index] == str[i]) {   // 같은 단어일 경우
                str.erase(str.begin() + i);
                i--;
            }
        }
        res.push_back(str[index]);
        str.erase(str.begin() + index);
    }

    // 출력 시작
    for (int i = 0; i < res.size(); i++) {
        cout << res[i] << endl;
    }

    return 0;
}

 

시간 초과 오류...

원인은 아직 찾지 못했다.

 

cin, cout 대신 scanf, printf 쓰면 더 빨라진다는 소리도 있는데 string 때문인건가.. ㅠㅠ