[BOJ] 1181번 : 단어 정렬
2024. 8. 30. 07:58ㆍAlgorithm
1. problem :
https://www.acmicpc.net/problem/1181
2. solution 1 :
#include <bits/stdc++.h>
using namespace std;
int n;
bool cmpw(const string& a, const string& b) {
if (a.size() != b.size()) return a.size() < b.size();
return a < b;
}
int main(void) {
ios::sync_with_stdio(0);
cin.tie(0);
cin >> n;
vector<string> v;
for (int i = 0; i < n; i++) {
string x;
cin >> x;
v.push_back(x);
}
sort(v.begin(), v.end(),cmpw);
int cnt = 1;
int idx = 1;
while (cnt < n) {
cnt++;
if (v[idx] == v[idx - 1]) v.erase(v.begin() + idx);
else idx++;
}
for (int i = 0; i < v.size(); i++) cout << v[i] << '\n';
}
3. solution 2 :
// Authored by : tongnamuu
// Co-authored by : -
// http://boj.kr/e365634189b1497a95abaf856df7758f
#include <bits/stdc++.h>
using namespace std;
int main(void){
ios::sync_with_stdio(0);
cin.tie(0);
int n;
cin>>n;
vector<string>a(n);
for(int i=0;i<n;++i) cin>>a[i];
sort(a.begin(), a.end(), [](const string& u, const string& v){
int ul = u.length();
int vl = v.length();
if(ul!=vl) return ul < vl;
return u < v;
});
a.erase(unique(a.begin(), a.end()), a.end()); // a에서 중복된 원소를 제거하는 명령
for(string& s : a) cout<<s<<'\n';
return 0;
}
source code 출처 : https://github.com/encrypted-def/basic-algo-lecture/blob/master/0x0F/solutions/1181.cpp
basic-algo-lecture/0x0F/solutions/1181.cpp at master · encrypted-def/basic-algo-lecture
바킹독의 실전 알고리즘 강의 자료. Contribute to encrypted-def/basic-algo-lecture development by creating an account on GitHub.
github.com
lambda 식을 이용한 cmp의 정의와 unique를 이용한 중복값 뒤로 보낸 후, 중복값을 삭제하는 과정이 흥미롭다. 외우자.
unique를 완료하면 trash값 첫 번째 원소를 가리킨다고 한다.
'Algorithm' 카테고리의 다른 글
| [BOJ] 7795번 : 먹을 것인가 먹힐 것인가 (0) | 2024.08.30 |
|---|---|
| [BOJ] 2910번 : 빈도 정렬 (0) | 2024.08.30 |
| [BOJ] 5648번 : 역원소 정렬 (0) | 2024.08.30 |
| [BOJ] 1914번 : 하노이 탑 (0) | 2024.08.29 |
| [BOJ] 11652번 : 카드 (0) | 2024.08.29 |