牛客 - 树上子链(树的直径-处理负权)
生活随笔
收集整理的這篇文章主要介紹了
牛客 - 树上子链(树的直径-处理负权)
小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,幫大家做個(gè)參考.
題目鏈接:點(diǎn)擊查看
題目大意:給出一棵樹,每個(gè)點(diǎn)都有權(quán)值,現(xiàn)在要求輸出樹上權(quán)值和最大的一條鏈
題目分析:讀完題后第一反應(yīng)是樹的直徑,趕緊去找來模板貼上,交上去WA了一發(fā)后意識(shí)到,正常樹的直徑只能處理非負(fù)邊權(quán),而這個(gè)題目中有負(fù)權(quán),然后就想用樹形dp亂搞試試,但奈何我的dp非常弱,搞到最后也沒搞出來,比賽時(shí)我想的是dp[ i ]代表的是從葉子結(jié)點(diǎn)到點(diǎn) i 為止最大的權(quán)值和,一路向上轉(zhuǎn)移,交上去一直WA,賽后看了別人的代碼意識(shí)到,這樣的dp無法處理以點(diǎn) i 為中間過渡點(diǎn)的子鏈,再后來才知道,這是一個(gè)樹的直徑處理負(fù)權(quán)的模板題,就當(dāng)長見識(shí)了吧,貼上模板直接過了
代碼:
#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<unordered_map> using namespace std;typedef long long LL;typedef unsigned long long ull;const int inf=0x3f3f3f3f;const int N=1e5+100;vector<int>node[N];LL dp[N],a[N],ans;void dfs(int u,int fa) {dp[u]=a[u];ans=max(ans,a[u]);for(auto v:node[u]){if(v==fa)continue;dfs(v,u);ans=max(ans,dp[u]+dp[v]);dp[u]=max(dp[u],dp[v]+a[u]);} }int main() { #ifndef ONLINE_JUDGE // freopen("input.txt","r",stdin); // freopen("output.txt","w",stdout); #endif // ios::sync_with_stdio(false);int n;scanf("%d",&n);ans=-inf;for(int i=1;i<=n;i++)scanf("%lld",a+i);for(int i=1;i<n;i++){int u,v;scanf("%d%d",&u,&v);node[u].push_back(v);node[v].push_back(u);}dfs(1,-1);printf("%lld\n",ans);return 0; }?
總結(jié)
以上是生活随笔為你收集整理的牛客 - 树上子链(树的直径-处理负权)的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: HDU - 3247 Resource
- 下一篇: 牛客 - 收集纸片(最短哈密顿路径-状压