牛客 - 点对最大值(树的直径)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - 点对最大值(树的直径)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:點擊查看
題目大意:給出 n 個點組成的一棵樹,每個點和每條邊都有權值,現在需要求出一對點 ( x , y ) ,使得點 x 到點 y 的唯一路徑權值和最大,權值和包括點 x 和點 y 的權值以及路徑上所有邊的權值之和
題目分析:比賽時沒注意到這是樹的直徑,在那里寫了一個小時的換根dp也沒寫出來,導致也沒時間去看其實很簡單的 G 題,感覺虧死了
樹的直徑模板題,只不過加了個限制是路徑上還需要加上兩個端點的權值,只需要稍微修改一下就好了
代碼:
#include<iostream> #include<cstdio> #include<string> #include<ctime> #include<cmath> #include<cstring> #include<algorithm> #include<stack> #include<climits> #include<queue> #include<map> #include<set> #include<sstream> #include<cassert> #include<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e6+100;struct Node {int to,w;Node(int to,int w):to(to),w(w){} };vector<Node>node[N];int a[N],dp[N],ans;//dp[i]代表以點i為根時,權值和最大的一條鏈,包含了一個端點的權值void dfs(int u,int fa) {dp[u]=a[u];for(auto t:node[u]){int v=t.to;int w=t.w;if(v==fa)continue;dfs(v,u);ans=max(ans,dp[u]+dp[v]+w);dp[u]=max(dp[u],dp[v]+w);} }void init() {for(int i=0;i<N;i++)node[i].clear();ans=-inf; }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);int w;cin>>w;while(w--){init();int n;scanf("%d",&n);for(int i=2;i<=n;i++){int to,w;scanf("%d%d",&to,&w);node[to].push_back(Node(i,w));node[i].push_back(Node(to,w));}for(int i=1;i<=n;i++)scanf("%d",a+i);dfs(1,-1);printf("%d\n",ans);}return 0; }?
總結
以上是生活随笔為你收集整理的牛客 - 点对最大值(树的直径)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: CodeForces - 1359E M
- 下一篇: 牛客 - 养花(最大流)