[Python][DFS]최장경로

 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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
def recur():
    global n
    if len(candidate) == n:
        l = candidate[:]
        result.append(l)
    else:
        for i in [0, 1]:
            candidate.append(i)
            recur()
            candidate.pop()

def sol():
    global n, k, answer
    for i in range(1 << n):
        tmp = 0
        for j in range(n):
            if i & (1 << j):
                tmp += a[j]
                print(a[j], end=" ")
        print()
        if tmp == k:
            answer += 1

def convert():
    global n
    for i in result:
        tmp = []
        for j in range(n):
            c = a[j] * i[j]
            tmp.append(c)
        aa.append(tmp)

for t in range(int(input())):
    n, k = map(int, input().split())
    a = list(map(int, input().split()))
    aa = list()
    result = []
    candidate = []


    answer = 0
    recur()
    tt = []
    for i in result:
        tmp = 0
        for j in range(n):
            if i[j] == 1:
                tmp += a[j]
        if tmp == k:
            tt.append(i)
            answer += 1
    print(tt)
    print("#{} {}".format(t+1, answer))

    print('-' * 50)
    answer = 0
    convert()
    print(aa)
    for i in aa:
        if sum(i) == k:
            answer += 1
    print("#{} {}".format(t + 1, answer))




    print('-'*50)
    answer = 0
    sol()
    print("#{} {}".format(t+1, answer))

댓글

이 블로그의 인기 게시물

[python]섬의 둘레구하기

백트래킹으로 부분집합구하기(Get Powerset usiing Backtracking)

[Python]DFS를 이용한 부분집합 구현