查找最大的偶数子树python

时间:2019-01-04 12:41:47

标签: python tree

i的输入如下,第一行是节点数(n),n个下一数字是权重,n-1个下一个数字是边,

6
9
3
6
7
8
2
2 1
3 1
4 2
5 3
6 3

这是我的代码

    def find_children(node_N,N,edges):
        children = []
        for m in range(N-1):
            if edges[m][1] == node_N:
                children.append(edges[m][0])
                children += find_children(edges[m][0],N,edges)
        return children

    from itertools import groupby

    def main():
        N = int(input())
        edges = []
        data = []
        for i in range(N):
            V = int(input())
            data.append(V)

        for x in range(N-1):
            L = str(raw_input())
            u , v = L.split()
            edges.append([int(v), int(u)])

        # create tree
        tree = []

        for n in range(N):
            tree.append([n+1])

        for n in range(N):
            tree[n].append(find_children(n+1,N,edges))    
        rr =[]
        tr = []
        for d in tree:
            gg = []
            gg.append(data[d[0]-1])
            for dd in d[1]:
                gg.append(data[dd-1])
            rr.append(gg)

        tr = [0] * len(rr)
        for i, l in enumerate(rr):
            counter = 0
            for v in l:
                if v % 2 == 0:
                    counter += 1
                else:
                    tr[i] = max(counter, tr[i])
                    counter = 0
            tr[i] = max(counter, tr[i])

        print(max(tr))

    main() 

但是它打印从根到叶的路径的最大偶数,并且不考虑其他状态,如何检查树中的所有路径。 在此示例中,最大的偶数子树是3,

0 个答案:

没有答案