알고리즘 공부

백준 1181번 단어 정렬 C++

빵어 2023. 9. 11. 22:14

vector를 이용한 코드

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

using namespace std;

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n = 0;
	cin >> n;

	vector<string> v;

	for (int i = 0; i < n; ++i) {
		string s = "";
		cin >> s;

		v.push_back(s);
	}

	sort(v.begin(), v.end(), [](string a, string b) {
		if (a.length() == b.length())
			return a < b;
		else
			return a.length() < b.length();
		});

	v.erase(unique(v.begin(), v.end()), v.end());

	for (string s : v)
		cout << s << '\n';

	return 0;
}

 

배열을 사용한 코드

#include <iostream>
#include <algorithm>

using namespace std;

string s[20001];

int main()
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);

	int n = 0;
	cin >> n;

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

	sort(s, s + n, [](string a, string b) {
		if (a.length() == b.length())
			return a < b;
		else
			return a.length() < b.length();
		});

	cout << s[0] << '\n';
	for (int i = 1; i < n; ++i) {
		if (s[i] == s[i - 1])
			continue;
		cout << s[i] << '\n';
	}

	return 0;
}

 

endl와 '\n' 차이로 결과가 많이 달라지는 문제

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

 

1181번: 단어 정렬

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

www.acmicpc.net