Tree dp: a stage without a boss

Stage without a boss


Title description A
university has N employees, numbered 1~N. There is a subordinate relationship between them, which means that their relationship is like a tree rooted by the principal, and the parent node is the direct boss of the child node. There is an anniversary banquet. Every time a staff member is invited to the banquet, a certain happiness index Ri will be increased. However, if the boss of a staff member comes to the ball, then the staff member will not come to the ball anyway. Therefore, please program and calculate which staff can be invited to maximize the happiness index and seek the greatest happiness index.
Input and output format
Input format:

An integer N in the first line. (1<=N<=6000)
Next N rows, the i+1th row represents the happiness index Ri of employee i. (-128<=Ri<=127)
Next N-1 lines, enter a pair of integers L and K for each line. Indicates that K is the immediate boss of L.
Enter 0 0 on the last line

Output format:

Output the largest happiness index.

Input and output sample
Input sample #1:
7
1
1
1
1
1
1
1
1 3
2 3
6 4
7 4
4 5
3 5
0 0
Output sample #1:
5
Idea:
We use the adjacency table to store user input The tree forms a tree-shaped dp, and then we first find the root node of the main for calculation, and change each child node in the function. dp[u][1]=kx[u] represents the joy index of the person who is numbering u, and then j=z[k] finds the next child node. If not, loop the child nodes of u.
Use dp[u][0] when the u number is not gone, and use dp[u][1] when it goes.
When the u number does not go, dp[u][0]+=max(dp[j][0],dp[j][1]), select the maximum possible value of his child nodes to go and not to go.
When the number u goes, dp[u][1]+=dp[j][0], so his children cannot go.
program:

def dfs(u):
    global dp
    dp[u][1]=kx[u]
    k=h[u]
    while k!=0:
        j=z[k]
        dfs(j)
        dp[u][0]+=max(dp[j][0],dp[j][1])
        dp[u][1]+=dp[j][0]
        k=nx[k]
    
n=int(input())
kx=[0]
c=[]
for i in range(n):
    kx.append(int(input()))
for i in range(n):
    c.append(list(map(int,input().split())))
c.pop()
nu=1
h=[0 for i in range(n+1)]
nx=[0 for i in range(n+1)]
z=[0 for i in range(n+1)]
dp=[[0 for i in range(2)] for i in range(n+1)]
fa=[0 for i in range(n+1)]
for i in range(n-1):
    fa[c[i][0]]=1
    z[nu]=c[i][0]
    nx[nu]=h[c[i][1]]
    h[c[i][1]]=nu
    nu+=1
for i in range(1,n):
    if fa[i]==0:
        dfs(i)
        s=i
        break
print(max(dp[s][0],dp[s][1]))

Reprinting is prohibited. Only for self-study. No responsibility for program errors.

Guess you like

Origin blog.csdn.net/weixin_46640345/article/details/112724881