티스토리 뷰

728x90

https://www.acmicpc.net/problem/2992

 

2992번: 크면서 작은 수

정수 X가 주어졌을 때, X와 구성이 같으면서 X보다 큰 수 중 가장 작은 수를 출력한다. 수의 구성이 같다는 말은, 수를 이루고 있는 각 자리수가 같다는 뜻이다. 예를 들어, 123과 321은 수의 구성이

www.acmicpc.net

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
import copy
 
X = input()
lst, L = [], len(X)
chk = {}
for idx in X:
    chk[idx] = chk.get(idx, 0) + 1
for i in range(int(X), 10**L):
    s = ''
    tmp = str(i)
    t = copy.deepcopy(chk)
    for n in range(len(tmp)):
        if tmp[n] in X and t[tmp[n]] > 0:
            s += tmp[n]
            t[tmp[n]] = t.get(tmp[n]) - 1
    if len(s) == len(X) and int(s) != int(X):
        lst.append(int(s))
lst.sort()
if lst:
    print(lst[0])
else:
    print(0)
cs

초기 구현 : 라이브러리 미사용

dictionary에 각 숫자 사용 횟수를 저장하여 하나씩 제거하며 최솟값 결정

속도는 느리지만 결과 출력

 

 

 

 

1
2
3
4
5
6
7
8
9
10
11
12
13
14
from itertools import permutations
 
= list(input().rstrip())
= int(''.join(X))
tmp = set()
for comb in permutations(X):
    if int(''.join(comb)) > x:
        tmp.add(int(''.join(comb)))
res = list(tmp)
res.sort()
if res:
    print(res[0])
else:
    print(0)
cs

itertools 라이브러리 사용

> permutations(iterable,r=None) : iterable에서 원소 개수가 r개인 순열 출력

 

ex) '1', '2', '3' -> '1','2','3'

                     '1','3','2'

                     '2','1','3'

                     '2','3','1'

                     '3','1','2'

                     '3','2','1' 

 

댓글