BOJ/🥈

★Combinatorics Upper-Intermediate I - 4 Solved★

metamong 2023. 8. 16.

★ 2697 다음수 구하기 ★

 

import sys
input=sys.stdin.readline

def next_permutation(n,l): #ex) n = [3,2,1]
    i = l-2

    while i>=0 and n[i]>=n[i+1]:
        i-=1
    
    if i>=0:
        j=l-1
        while n[j] <= n[i]:
            j-=1
        n[i],n[j]=n[j],n[i]
        n[i+1:] = reversed(n[i+1:])
        return n
    else:
        return 'BIGGEST'

for _ in range(int(input())):
    A=list(map(int,input().strip()))#ex)[1,2,3]
    res = next_permutation(A,len(A)) #ex)[1,3,2]
    if res == 0: print('USELESS')
    else: print(*res,sep='') #ex) 132

 

next_permutation


★ 5360 Next Permutation ★

 

def next_permutation(n,l):
    i = l-2
    while i >=0 and n[i] >= n[i+1]:
        i-=1
    
    if i>=0:
        j = l-1
        while n[j] <= n[i]:
            j-=1
        n[i],n[j] = n[j],n[i]
        n[i+1:] = reversed(n[i+1:])
        return n
    else:
        return 0

for _ in range(int(input())):
    A=list(map(int,input().strip()))#ex)[1,2,3]
    res = next_permutation(A,len(A)) #ex)[1,3,2]
    if res == 0: print('USELESS')
    else: print(*res,sep='') #ex) 132

 

 next_permutation


★ 10972 다음 순열 ★

 

import sys
input=sys.stdin.readline

N=int(input())
l=list(map(int,input().split()))

def next_permutation(l,N):
    i=N-2
    while i>=0 and l[i]>=l[i+1]:
        i-=1

    if i>=0:
        j=N-1
        while l[j]<=l[i]:
            j-=1
        l[i],l[j]=l[j],l[i]
        l[i+1:]=reversed(l[i+1:])
        return l
    else:
        return -1

res = next_permutation(l,N)
if res == -1: print(-1)
else: print(*res)

 

 next_permutation


★ 20529 가장 가까운 세 사람의 심리적 거리 ★

 

import sys
input=sys.stdin.readline
from itertools import combinations

for _ in range(int(input())):
    nums=int(input())
    MBTIs=list(input().split())

    #pigeonhole principle
    #n=16, K+1=3 -> nK+1=33
    if nums>32:
        print(0)
    else:
        ans=[]
        for three_in_pair in combinations(MBTIs,3):
            x,y,z=three_in_pair[0],three_in_pair[1],three_in_pair[2]
            total=0
            for pair in [(x,y),(y,z),(x,z)]:
                xx,yy=pair[0],pair[1]
                total+=(len(set(list(xx)+list(yy)))-4)
            ans.append(total)
        print(min(ans))

 

비둘기집 원리에 의해 32보다 많은 쌍에서는 무조건 심리적 거리가 0인 경우 존재. 나머지는 32C3으로 combination 직접 돌리면 된다.


 

 

 

 

 

 

 

 

 

 

댓글