백준 링크 : https://www.acmicpc.net/problem/1181

문제 개요

N개의 입력만큼 문자열이 들어오는데, 이 문자열을 길이가 짧은 순으로 그리고 사전순으로 정렬하는 것이다. 정렬과정에서 중복되는 문자열은 1개만 남겨두고 삭제한다.

아이디어


코드


// 아래의 코드는 dev c++환경에서 동작됩니다.
// visual studio에서는 bit/stdc++.h가 기본적으로 없기 때문에
// 정삭적인 작동이 되지 않을 수 있습니다.
#include <bits/stdc++.h>
using namespace std;

int n;
string s;
vector<string> a;

bool comp(const string& lhs, const string& rhs)
{
	if(lhs.length() < rhs.length()) // 짧은 길이 순 정렬
	{
		return true;
	}		
	else if(lhs.length() == rhs.length()) 
	{
		return lhs < rhs; // 사전 순 정렬
	}
	return false;
}

int main()
{
  ios::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL);
	cin >> n;
	for(int i = 0; i < n; i++)
	{
		cin >> s;
		a.push_back(s);
	}
	
	sort(a.begin(), a.end(), comp);
	a.erase(unique(a.begin(), a.end()), a.end()) ;
	for(auto& str : a) cout << str << "\\n";
  return 0;
}

후기


처음에 string::operator<가 사전순으로 정렬인지 모르고 복잡한 로직을 통해 사전순 비교를 구현했다. 앞으로 사전순 비교가 나왔을 때는 string::operator<를 자주 애용할 것 같다.