日韩性视频-久久久蜜桃-www中文字幕-在线中文字幕av-亚洲欧美一区二区三区四区-撸久久-香蕉视频一区-久久无码精品丰满人妻-国产高潮av-激情福利社-日韩av网址大全-国产精品久久999-日本五十路在线-性欧美在线-久久99精品波多结衣一区-男女午夜免费视频-黑人极品ⅴideos精品欧美棵-人人妻人人澡人人爽精品欧美一区-日韩一区在线看-欧美a级在线免费观看

歡迎訪問 生活随笔!

生活随笔

當前位置: 首頁 > 编程资源 > 编程问答 >内容正文

编程问答

NYOJ 679 The Weight of Tree 搜索+dp+邻接表

發布時間:2025/3/16 编程问答 37 豆豆
生活随笔 收集整理的這篇文章主要介紹了 NYOJ 679 The Weight of Tree 搜索+dp+邻接表 小編覺得挺不錯的,現在分享給大家,幫大家做個參考.

The Weight of Tree

時間限制:3000?ms ?|? 內存限制:65535?KB 難度:4 描述
456 has a tree of n nodes, each node is assigned with an integer number. Now 456 wants to select a subtree, such that the sum of all integers on the nodes of the subtree is maxmized. Can you help him?? 輸入
On the first line of the input is an integer T, and then T cases follows. Each case begins with a positive integer n(1 <= n <= 10^5), then n numbers Wi(-1000 <= Wi <= 1000),Wi for the number on the ith node. Then n - 1 lines follows, each line contains two numbers a, b(1 <= a, b <= n)indicate that there is a edge between node a and b.
輸出
For each test case, output one integer on a line, the maximized sum can be achieved by selecting a subtree.?
樣例輸入
3 1 5 2 5 -5 1 2 5 -2 -3 7 -1 4 1 2 2 3 3 4 2 5

樣例輸出

5 5 8 ? ? 從第一個點一直往下深搜,然后回溯,判斷子節點的值是否大于0,如果大于0,父節點的值變為當前的值加上子節點的值。最后輸出最大值即可。

#include<stdio.h> #include<string.h> #include<vector> #include<algorithm> #define N 100005 using namespace std; vector<int> vec[N]; int vis[N],dp[N],MAX; void dfs(int x) {vis[x]=1;for(int i=0;i<vec[x].size();i++){int y=vec[x][i];if(vis[y])continue;dfs(y);if(dp[y]>0)dp[x]+=dp[y];MAX=max(dp[x],MAX);} } int main() {int t,n,i,a,b;scanf("%d",&t);while(t--){memset(vis,0,sizeof(vis));memset(vec,0,sizeof(vec));scanf("%d",&n);MAX=-999999;for(i=1;i<=n;i++){scanf("%d",&dp[i]);MAX=max(dp[i],MAX);}for(i=1;i<n;i++){scanf("%d%d",&a,&b);vec[a].push_back(b);vec[b].push_back(a);}dfs(1);printf("%d\n",MAX);}return 0; }


總結

以上是生活随笔為你收集整理的NYOJ 679 The Weight of Tree 搜索+dp+邻接表的全部內容,希望文章能夠幫你解決所遇到的問題。

如果覺得生活随笔網站內容還不錯,歡迎將生活随笔推薦給好友。