题目链接:点击查看
题目大意:给出一棵树,每个点都有权值,现在要求输出树上权值和最大的一条链
题目分析:读完题后第一反应是树的直径,赶紧去找来模板贴上,交上去WA了一发后意识到,正常树的直径只能处理非负边权,而这个题目中有负权,然后就想用树形dp乱搞试试,但奈何我的dp非常弱,搞到最后也没搞出来,比赛时我想的是dp[ i ]代表的是从叶子结点到点 i 为止最大的权值和,一路向上转移,交上去一直WA,赛后看了别人的代码意识到,这样的dp无法处理以点 i 为中间过渡点的子链,再后来才知道,这是一个树的直径处理负权的模板题,就当长见识了吧,贴上模板直接过了
代码:
#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)
{
LL mmax=0;
dp[u]=a[u];
ans=max(ans,a[u]);
for(auto v:node[u])
{
if(v==fa)
continue;
dfs(v,u);
ans=max(ans,mmax+a[u]+dp[v]);
mmax=max(mmax,dp[v]);
}
dp[u]+=mmax;
}
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;
}