본문 바로가기
PS(Problem Solving)/백준_BOJ

[백준] 1181번 - 단어 정렬 (C++/파이썬) 문제 및 풀이

by 초코칩프라푸치노 2021. 4. 14.

문제) 백준 - 정렬(Sort) -  단어 정렬

-> www.acmicpc.net/problem/1181

 

1181번: 단어 정렬

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

www.acmicpc.net

길이가 짧은 순으로 정렬해주되, 길이가 같을 경우 사전 순으로 정렬한다.

자신이 사용하는 언어의 정렬 Tool을 잘 활용한다면 어렵지 않은 문제. 

 

 

C++ 소스 코드)

 

#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;
}
view raw 1181.cpp hosted with ❤ by GitHub

 

파이썬 소스 코드)

 

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])
view raw 1181.py hosted with ❤ by GitHub

 

 

반응형

댓글