Little Jay

[C++] 백준 1181번 단어 정렬 본문

알고리즘/BOJ

[C++] 백준 1181번 단어 정렬

Jay, Lee 2021. 8. 2. 19:13

algorithm 헤더에는 sort라는 기능이 있는데

그 기능에 약간 손을 봐주면 되는 문제

sort 기능에 마지막 세 번째에 함수를 넣어 주어서

그 함수의 return값대로 정렬을 하면 되는 문제이다

이번 문제에서는 compare이라는 함수를 사용해서

단어의 길이를 비교해주어 sort하도록 유도했다

 

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

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

int main() {

	int n;
	cin >> n;
	string s, temp;
	vector<string> v;
	for (int i = 0; i < n; i++) {
		cin >> s;
		v.push_back(s);
	}

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

	for (int i = 0; i < n; i++) {
		if (temp == v[i])
			continue;
		cout << v[i] << "\n";
		temp = v[i];
	}


	return 0;
}

'알고리즘 > BOJ' 카테고리의 다른 글

[C++] 백준 1021번 회전하는 큐  (0) 2021.08.04
[C++] 백준 4949번 균형잡힌 세상  (0) 2021.08.03
1783번 병든 나이트  (0) 2021.08.02
[C++] 백준 2875번 대회 or 인턴  (0) 2021.08.02
[C++] 백준 11047번 동전 0  (0) 2021.08.02
Comments