728x90
https://www.acmicpc.net/problem/1181
1181번: 단어 정렬
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
www.acmicpc.net
시간 제한메모리 제한제출정답맞힌 사람정답 비율
2 초 | 256 MB | 167029 | 69955 | 52446 | 40.378% |
문제
알파벳 소문자로 이루어진 N개의 단어가 들어오면 아래와 같은 조건에 따라 정렬하는 프로그램을 작성하시오.
- 길이가 짧은 것부터
- 길이가 같으면 사전 순으로
단, 중복된 단어는 하나만 남기고 제거해야 한다.
입력
첫째 줄에 단어의 개수 N이 주어진다. (1 ≤ N ≤ 20,000) 둘째 줄부터 N개의 줄에 걸쳐 알파벳 소문자로 이루어진 단어가 한 줄에 하나씩 주어진다. 주어지는 문자열의 길이는 50을 넘지 않는다.
출력
조건에 따라 정렬하여 단어들을 출력한다.
예제 입력 1 복사
13
but
i
wont
hesitate
no
more
no
more
it
cannot
wait
im
yours
예제 출력 1 복사
i
im
it
no
but
more
wait
wont
yours
cannot
hesitate
//solution
def sort_ascending_string(a):
words = set()
for i in range(a):
word = input()
words.add(word)
words = list(words)
for i in range(1, len(words)):
for j in range(i, 0 ,-1):
if len(words[j-1])==len(words[j]):
if words[j-1] > words[j]:
words[j-1], words[j] = words[j], words[j-1]
elif len(words[j-1])>len(words[j]):
words[j-1], words[j] = words[j], words[j-1]
for word in words:
print(word)
a = int(input())
sort_ascending_string(a)
처음에는 위 코드처럼 삽입정렬 사용했다가 시간초과가 떴다.
보니까 문자열도 정렬이 가능했다.
def sort_ascending_string(a):
words = set(input() for _ in range(5))
words.sorted(key=len)
for word in words:
print(word)
a = int(input())
sort_ascending_string(a)
그리고 이런식으로 풀었는데 런타임에러가 떴다.
구글링을 해보니까 input() 과 sys.stdin.readline() 이거에 속도차이가 1/10 수준이다.
import sys
n = int(input())
words = [sys.stdin.readline().strip() for i in range(n)]
words = list(set(words))
words.sort()
words.sort(key=len)
for i in words:
print(i)
이렇게 고치니 됐다.
728x90
'[python] > 알고리즘 공부' 카테고리의 다른 글
!백준 18870 좌표압축 [python] (0) | 2024.01.09 |
---|---|
백준 1427 소트인사이드 (1) | 2024.01.07 |
백준 세로읽기 [python] x (0) | 2023.07.31 |
백준 행렬 덧셈 [python] (0) | 2023.07.28 |
백준 25206 너의 평점은 [python] (0) | 2023.07.23 |