传送门:
思路:就是在树的直径问题上把每条边都变成了负权边同时在每一个节点上面加多了一个权值,在输的直径问题的代码上稍作修改,让返回值变成max(当前节点的权值,当前节点的权值加上向下能扩展的最大权),因为向下的扩展有可能为负数,所以干脆不如只到当前节点就返回更加合理。
代码:
#include<iostream>
#include<algorithm>
#include<cstring>
#include<unordered_map>
#include<stack>
using namespace std;
typedef long long ll;
const int N=3e5+10,pp=131;
int e[N*2],ne[2*N],w[2*N],h[N],idx;
int n;
ll ans;
ll a[N];
void add(int a,int b,int c)
{
e[idx]=b,w[idx]=c,ne[idx]=h[a],h[a]=idx++;
}
ll dfs(int u,int father)
{
ll d1=0,d2=0;
ll dist=0;
for(int i=h[u];~i;i=ne[i])
{
int j=e[i];
if(j==father) continue;
ll d=dfs(j,u)-w[i];
dist=max(dist,d);
if(d>=d1) d2=d1,d1=d;
else if(d>d2) d2=d;
}
ans=max(ans,d1+d2+a[u]);
dist=max(dist+a[u],a[u]);
return dist;
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d",&n);
for(int i=1;i<=n;i++)
scanf("%lld",&a[i]);
for(int i=1;i<n;i++)
{
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
add(x,y,z);
add(y,x,z);
}
dfs(1,-1);
cout<<ans<<endl;
return 0;
}