본문 바로가기

코딩 이야기/백준 풀이

백준 1181번: 단어 정렬 C++코드(정렬)

반응형

#include<iostream>
#include<vector>
#include<algorithm>
#include<utility>
#include<string>

using namespace std;

bool cmp(const string & a, const string & b){
    if(a.length() < b.length()) return true;
    else if(a.length() == b.length()){
        if(a < b) return true;
    }
    return false;
}


int main(){
    int n;
    char temp[51];
    vector <string> words; 
    scanf("%d", &n);
    for(int i=0; i<n; i++){
        int state = 0;
        scanf("%s", temp);
        words.push_back(temp);
    }
    string temp2;
    sort(words.begin(), words.end(), cmp);
    for(int i=0; i<n; i++){
        if(i == 0){
            temp2 = words[i].c_str();
            printf("%s\n", words[i].c_str());
        }else{
            if(temp2 != words[i].c_str()){
                printf("%s\n", words[i].c_str());
                temp2 = words[i].c_str();
            }else{
                continue;
            }
        }
    }
        
}
설명

단어의 길이를 우선으로 정렬하고 그 후에 알파벳순으로 정렬하는 함수cmp를 만들어주고 이를 sort함수에 넣어서 정렬하면, 문제에서 요구하는데로 정렬된다. 그 후에 벡터 안에 있는 값을 뽑으면서 값을 temp2에 저장해뒀다가 다른 값이 나오면 temp2를 그 값으로 수정하고, 그 값을 출력한다. 반대로 temp2와 같은 값이 나오면 그냥 continue해준다.

 

문제점

중복되는 값을 제거할 때, 처음에는 벡터에 값을 넣을때 여태껏 넣은 벡터에 있는 지 검사하는 식으로 제거했는데, 이는 시간복잡도를 너무 많이 잡아먹어서 지금처럼 수정하였다.

반응형