Algorithm/Sorting

Baekjoon 1181 단어 정렬

GirlFriend_Yerin 2019. 8. 22. 13:15

Link https://www.acmicpc.net/problem/1181

소스결과 3944 KB / 20 ms

출처 Baekjoon

언어 C++ 17

분류 정렬

 

설명

단어를 주어진 조건대로 정렬하여 출력하자.

 

string이 아닌 char*로 넘겨 받아서 처리한다면 난이도가 조금 올라가는 문제

주어진 조건에 맞게 비교할 수 있는 cmp 함수를 만들면된다.

string 을 사용한다면 사전순 정렬은 operator가 정의되어 있어 쉽다.

 

소스코드

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

using namespace std;

bool cmp(string& str1, string& str2) {


	if (str1.length() == str2.length())
		return str1 < str2;
	return str1.length() < str2.length();
}

int main()
{
	ios_base::sync_with_stdio(false);
	cin.tie(0);

	int n; cin >> n;

	vector<string> inputs(n);

	for (int i = 0; i < n; i++)
		cin >> inputs[i];

	sort(inputs.begin(), inputs.end(), cmp);

	string checker = inputs[0];
	cout << inputs[0] << '\n';

	for (int i = 1; i < n; i++) {
		if (inputs[i] != checker) {
			cout << inputs[i] << '\n';
			checker = inputs[i];
		}
	}
	return 0;
}