๋ณธ๋ฌธ ๋ฐ”๋กœ๊ฐ€๊ธฐ
  • What would life be If we had no courage to attemp anything?
Problem Solving/SWEA

swea4021.์š”๋ฆฌ์‚ฌ

by DevIseo 2022. 4. 7.

https://swexpertacademy.com/main/code/problem/problemDetail.do?contestProbId=AWIeUtVakTMDFAVH 

 

SW Expert Academy

SW ํ”„๋กœ๊ทธ๋ž˜๋ฐ ์—ญ๋Ÿ‰ ๊ฐ•ํ™”์— ๋„์›€์ด ๋˜๋Š” ๋‹ค์–‘ํ•œ ํ•™์Šต ์ปจํ…์ธ ๋ฅผ ํ™•์ธํ•˜์„ธ์š”!

swexpertacademy.com

#์š”๋ฆฌ์‚ฌ

T = int(input())
for tc in range(1,T+1):
    N= int(input())
    arr = [list(map(int,input().split())) for _ in range(N)]
    answer = 999999999
    #DFS๋กœ ํ’€์–ด์•ผํ•  ๋“ฏ..
    #์š”๋ฆฌ 2๊ฐœ๋‹ˆ๊นŒ ์žฌ๋ฃŒ ๋‚˜๋ˆŒ๊ฒƒ. -๊ฐ™์€ ์‹์žฌ๋ฃŒ ์ˆ˜์ผ๋•Œ ์ˆ˜๋ฅผ ๋น„๊ต ํ•ด์•ผํ•จ!
    #level==N
    #DFS ์š”๋ฆฌA,์š”๋ฆฌB ๋‚˜๋ˆ ์„œ ์žฌ๊ท€ (์‹์žฌ๋ฃŒ ์ธ๋ฑ์Šค๋ฅผ ๋‚˜๋ˆ„๋Š” ๊ณผ์ •(?))

    def cook(level,Acook,Bcook):
        global answer
        if level==N: #์‹์žฌ๋ฃŒ ์ˆ˜๋งŒํผ level์ด ๋˜๋ฉด return!
            if len(Acook) == len(Bcook): #์‹์žฌ๋ฃŒ๋Š” ์ง์ˆ˜๋กœ ๋ฐ˜๋ฐ˜์ด๋‹ˆ๊นŒ ๊ฐ™์„๋•Œ!
                A,B=0,0
                for i in range(N//2):
                    for j in range(N//2):
                        A+=arr[Acook[i]][Acook[j]]
                        B+=arr[Bcook[j]][Bcook[i]]
                if answer>abs(A-B):
                    answer = abs(A-B)
            return

        cook(level+1,Acook+[level],Bcook) #A์š”๋ฆฌ์— ๋“ค์–ด๊ฐˆ ์‹์žฌ๋ฃŒ ๋ฒˆํ˜ธ
        cook(level+1,Acook,Bcook+[level]) #B์š”๋ฆฌ์— ๋“ค์–ด๊ฐˆ ์‹์žฌ๋ฃŒ ๋ฒˆํ˜ธ

    cook(0,[],[]) #level,A์š”๋ฆฌ,B์š”๋ฆฌ
    print(f'#{tc} {answer}')

ํ’€์ด ๊ณผ์ •

์ „์— DFS๋ฅผ ๊ณต๋ถ€ํ–ˆ์„ ๋•Œ 2๊ฐ€์ง€ ๊ฐ€์ง€๋กœ ๋‚˜๋‰˜๋Š” ๋ฐฉ๋ฒ•์„ ์‘์šฉํ•จ.

1. A์š”๋ฆฌ์— ๋“ค์–ด๊ฐˆ ์‹์žฌ๋ฃŒ์˜ ์ธ๋ฑ์Šค์™€ B์š”๋ฆฌ์— ๋“ค์–ด๊ฐˆ ์‹์žฌ์˜ ์ธ๋ฑ์Šค๋ฅผ ๋‹ด์•„ ์ค„ ๋ฆฌ์ŠคํŠธ๋ฅผ ๋งค๊ฐœ๋ณ€์ˆ˜๋กœ ์ง€์ •ํ•ด DFS๋Œ๋ฆฌ๊ธฐ

2. ์ข…๋ฃŒ ์กฐ๊ฑด์€ ์‹์žฌ๋ฃŒ์˜ ์ˆ˜ ์ผ๋•Œ!

3. ๋ฌธ์ œ์—์„œ ์ง์ˆ˜์˜ ์‹์žฌ๋ฃŒ๋ฅผ ์ œ๊ณตํ•˜๊ณ  ์š”๋ฆฌ์—๋Š” ์ ˆ๋ฐ˜์”ฉ ๋“ค์–ด๊ฐ„๋‹ค๊ณ  ์กฐ๊ฑด์ด ์ฃผ์–ด์กŒ์œผ๋ฏ€๋กœ if๋ฌธ์— ์กฐ๊ฑด์„ ๋‹ฌ์•„์ค„๊ฒƒ

4. for๋ฌธ์„ ๋Œ๋ ค์„œ ๊ฐ ์š”๋ฆฌ๋ณ„๋กœ ์‹์žฌ๋ฃŒ ๊ฐ’ ๋”ํ•ด์ฃผ๊ณ  

5. abs๋กœ ์ฐจ์ด ๊ตฌํ•ด์„œ ์ตœ์†Œ๊ฐ’์„ ๋‹ต์œผ๋กœ ๊ฐฑ์‹ 

๋Œ“๊ธ€