Algorithm/Baekjoon

[백준] 10819 차이를 최대 파이썬 python

rrojin 2022. 2. 22. 13:07

문제링크

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

 

10819번: 차이를 최대로

첫째 줄에 N (3 ≤ N ≤ 8)이 주어진다. 둘째 줄에는 배열 A에 들어있는 정수가 주어진다. 배열에 들어있는 정수는 -100보다 크거나 같고, 100보다 작거나 같다.

www.acmicpc.net

 

코드

방법1 permutations사용

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
import sys
from itertools import permutations
 
input = sys.stdin.readline
 
= int(input())
= list(map(int,input().split()))
 
all = permutations(a)
ans = 0
 
for i in all:
    s = 0
    for j in range(1,n):
        s+=abs(i[j]-i[j-1])
    if ans<s:
        ans =s
print(ans)
cs

 

방법2  permutations 직접 구현

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
import sys
 
input = sys.stdin.readline
 
= int(input())
= list(map(int,input().split()))
 
all =[]
def bf(arr, cur):
    if arr:
        for i in range(n-len(cur)):
            tmp = list(cur)
            tmp.append(arr[i])
            new_arr = arr[:i]+arr[i+1:]
            bf(new_arr, tmp)
    else:
        all.append(cur)
 
= sorted(a)
bf(a,[])
 
ans = 0
print(all)
for i in all:
    s = 0
    for j in range(1,n):
        s+=abs(i[j]-i[j-1])
    if ans<s:
        ans =s
print(ans)
cs

 

POINT

방법1

라이브러리를 사용하여(itertools.permutations(a)) 만들 수 있는 모든 순열을 만들고 차이 합을 구해서 비교한다. 

 

방법2

직접 모든 순열 구하는 알고리즘을 구현하고 차이 합을 비교한다. 

모든 순열 구하는 알고리즘은 아래 문제에서 구현한 것을 사용한다. 

https://rrojin.tistory.com/48

 

[백준] 10974 모든 순열 파이썬 python

문제링크 https://www.acmicpc.net/problem/10974 10974번: 모든 순열 N이 주어졌을 때, 1부터 N까지의 수로 이루어진 순열을 사전순으로 출력하는 프로그램을 작성하시오. www.acmicpc.net 코드 방법1 1 2 3 4 5..

rrojin.tistory.com