1 条题解

  • 0
    @ 2025-9-9 23:46:00

    C++ :

    #include<stdio.h>
    #include<string.h>
    #include<vector>
    #define M 6007
    using namespace std;
    vector<int>v[M];
    int vis[M],dp[M][2],happy[M],pre[M];
    int n;
    int max(int a,int b)
    {
        return a>b?a:b;
    }
    int dfs(int root)
    {
        vis[root]=1;
        dp[root][0]=happy[root];
        int len=v[root].size();
        for(int i=0;i<len;i++)
        {
            if(!vis[v[root][i]])
            {
                dfs(v[root][i]);
            }
            dp[root][1]+=max(dp[v[root][i]][0],dp[v[root][i]][1]);
            dp[root][0]+=dp[v[root][i]][1];
        }
    }
    int main()
    {
        while(scanf("%d",&n)!=EOF)
        {
            for(int i=1; i<=n; i++)
            {
                scanf("%d",&happy[i]);
                dp[i][0]=dp[i][1]=0;
                vis[i]=0;
                pre[i]=-1;
                v[i].clear();
            }
            int a,b;
            for(int i=1;i<n;i++)
            {
                scanf("%d%d",&a,&b);
                v[b].push_back(a);
                pre[a]=b;
            }
            a=1;
            while(pre[a]!=-1)a=pre[a];
            dfs(a);
            printf("%d\n",max(dp[a][1],dp[a][0]));
        }
        return 0;
    }
    
    
    • 1

    信息

    ID
    935
    时间
    1000ms
    内存
    256MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者