알고리즘 풀이/백준(Boj)

백준(BOJ) 1181번 단어 정렬

100win10 2019. 7. 31. 13:38

문제: https://www.acmicpc.net/problem/1181


문제

알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.

  1. 길이가 짧은 것부터
  2. 길이가 같으면 사전 순으로


나의풀이 :


1. string 배열을 만들어 담는다

2. size를 기준으로 정렬 한다 + 길이가 같을시 사전순으로 정렬 compare 만든다.

3. unique를 통해 중복을 제거 해준다.

unique에 관한 설명은 www.cppreference.com에 가셔서 검색하시면 보다 자세히 알 수 있습니다.

cppreference.com


코드 ( C++ )


#include <iostream>

#include <vector>

#include <string>

#include <algorithm>

using namespace std;


int N;

bool compare(string a, string b)

{

int as = a.size();

int bs = b.size();

if (as != bs)

{

return as < bs; // 사이즈대로 정렬

}

else

{

return a < b; // 사이즈가 같을시 사전순 정렬

}

}

int main()

{

ios_base::sync_with_stdio(false);

cin.tie(0);

vector<string> v;

cin >> N;

for (int i = 0; i < N; ++i)

{

string s;

cin >> s;

v.push_back(s);

}

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

// 중복을 없애자.

auto last = unique(v.begin(), v.end());

v.erase(last, v.end());

for (int i = 0; i < v.size(); ++i)

{

cout << v[i] << endl;

}

return 0;

}