문제) 백준 - 정렬(Sort) - 단어 정렬
-> www.acmicpc.net/problem/1181
1181번: 단어 정렬
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
www.acmicpc.net
길이가 짧은 순으로 정렬해주되, 길이가 같을 경우 사전 순으로 정렬한다.
자신이 사용하는 언어의 정렬 Tool을 잘 활용한다면 어렵지 않은 문제.
C++ 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <bits/stdc++.h> | |
#define endl "\n" | |
using namespace std; | |
vector<string> words; | |
bool compare(string x, string y) { | |
if (x.size() == y.size()) return x < y; | |
return x.size() < y.size(); | |
} | |
int main() { | |
int n; | |
cin >> n; | |
words.resize(n); | |
for (int i = 0; i < n; ++i) | |
cin >> words[i]; | |
//정렬 | |
sort(words.begin(), words.end(), compare); | |
//중복 제거 | |
words.erase(unique(words.begin(), words.end()), words.end()); | |
for (int i = 0; i < words.size(); ++i) | |
cout << words[i] << endl; | |
return 0; | |
} |
파이썬 소스 코드)
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import heapq | |
import sys | |
def heap_sort(a): | |
heap = [] | |
for i in a: | |
heapq.heappush(heap, i) | |
for i in range(len(a)): | |
a[i] = heapq.heappop(heap) | |
N = int(sys.stdin.readline().rstrip()) | |
alpha_list = [] | |
count = N | |
for i in range(N): | |
tmp = sys.stdin.readline().rstrip() | |
if (len(tmp), tmp) in alpha_list: | |
count -= 1 | |
continue | |
alpha_list.append((len(tmp),tmp)) | |
heap_sort(alpha_list) | |
for i in range(count): | |
print(alpha_list[i][1]) |
반응형
'PS(Problem Solving) > 백준_BOJ' 카테고리의 다른 글
[백준] 11279번 - 최대 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
---|---|
[백준] 1927번 - 최소 힙 (C++/파이썬) 문제 및 풀이 (0) | 2021.04.14 |
[백준] 1991번 - 트리 순회 (C++/파이썬) (0) | 2021.04.14 |
[백준] 2437번 - 저울 (C++/파이썬) (0) | 2021.04.13 |
[백준] 2503번 - 숫자야구 (C++) 문제 및 풀이 (0) | 2021.04.13 |
댓글