백준 1181 단어 정렬 C++

2023. 9. 13. 21:21알고리즘문제 풀이/백준

문제

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

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

입력

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

출력

조건에 따라 정렬하여 단어들을 출력한다. 단, 같은 단어가 여러 번 입력된 경우에는 한 번씩만 출력한다.

알고리즘 분류

풀이

단어는 벡터를 받는다.

정렬 알고리즘을 사용한다.

이를 위해 #include<algorithm>을 추가한다.

sort(v.begin(), v.end(), compare)은 vector의 시작과 끝을 compare을 기준으로 분류하라는 것이다.

bool compare(string a, string b)에서

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

으로 분류 기준을 정한다.

그 후 정렬된 단어들을 출력한다.

#include<iostream>
#include<string>
#include<vector>
#include<algorithm>
using namespace std;

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

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

	vector<string> v;
	int n;
	string s;
	string temp = "";

	//the number of words
	cin >> n;
	
	//enter words
	for (int i = 0; i < n; i++) {
		cin >> s;
		v.push_back(s);
	}

	//sort the words
	sort(v.begin(), v.end(), compare);

	//print the words
	//if the same words are entered multiple times, print them only one time.
	for (int i = 0; i < v.size(); i++) {
		if (temp != v[i]) {
			cout << v[i] << '\n';
			temp = v[i];
		}
	}

	return 0;
}

 

 

'알고리즘문제 풀이 > 백준' 카테고리의 다른 글

백준 1237 정ㅋ벅ㅋ C  (1) 2023.09.14
백준 1197 최소 스패닝 트리 C++  (0) 2023.09.14
백준 1167 트리의 지름 C++  (0) 2023.09.13
백준 1157 단어 공부 C++  (0) 2023.09.12
백준 1152 단어의 개수 Python  (0) 2023.09.11