NYOJ 697 The Weight of Tree

题目链接:here~~

树形dp

 

#include <iostream>

#include <cstdio>

#include <string.h>

#include <vector>

using namespace std;

bool vis[100010];

int point[100010];

vector<int> m[100010];

int maxn;

int dfs(int i)

{

    vis[i]=1;

    int res=point[i], term, len=m[i].size();

    for (int j=0; j<len; j++)

    {

        if (vis[m[i][j]]==0)

        {

            term=dfs(m[i][j]);

            if (term>0) res+=term;//如果大于0,就加上,小于0不操作

        }

    }

    if (maxn<res) maxn=res;//更新最大值

    return res;

}

int main()

{

//	freopen("in", "r", stdin);

	int T, n, i, a, b;

	scanf("%d", &T);

	while (T--)

	{

	    memset(vis, 0, sizeof (vis));

	    scanf("%d", &n);

	    for (i=1; i<=n; i++)

	        scanf("%d", &point[i]);

	    for (i=1; i<n; i++)

	    {

	        scanf("%d%d", &a, &b);

	        m[a].push_back(b);

	        m[b].push_back(a);

	    }

	    maxn=1<<31;

	    dfs(1);

	    printf("%d\n", maxn);

	    for (i=1; i<=n; i++) m[i].clear();

	}

	return 0;

}


 


 

你可能感兴趣的:(tree)