链接:https://ac.nowcoder.com/acm/contest/5758/A
来源:牛客网
这里有一棵树,每个点和每条边都存在一个价值。对于树上点对的价值,包括点对的起点和终点以及路径上边权值之和,不包括路径上其他点值。
求这颗树上最大的点对价值为多少。点对至少需要两个点。
输入描述:
输入t,代表有t组样例。每组样例第一行输入n,代表有n个点。接下来有n-1行,第i行有a[i]和b[i],代表a[i]节点与i节点存在一条边,且边的值为b[i],2<=i<=n。接下来一行有n个值c[j],代表每个节点j的价值,1<=j<=n。
(t<=10,n>1,n<1e6,a[i]<i,-500<=b[i]<=500,-500<=c[j]<=500)
输出描述:
输出最大的点对价值
示例1
输入
复制
1
4
1 -2
1 2
1 3
2 -2 3 4
输出
复制
12
边和节点值是分开判断的,不断判断加最大边,动态判断加边之后是否可以加节点值结束
最大点对:起点+终点+路径长度(中间节点值不计)
#include <iostream>
#include <stdio.h>
#include <algorithm>
using namespace std;
struct{
int father; //父节点
int value; //父节点到i的权值
}b[1000001];
int c[1000001]; //i的节点值
int main()
{
int T;
cin>>T;
while(T--)
{
int n;
cin>>n;
int ans,amax;
bool amaxis=false;
for(int i=2;i<=n;i++)
{
int father,value;
cin>>father>>value;
b[i].father=father;
b[i].value=value;
}
for(int i=1;i<=n;i++)
cin>>c[i];
for(int i=n;i>=2;i--)//从叶子节点走
{
//动态判断加边之后是否可以加节点值结束
int temp=c[i]+b[i].value+c[b[i].father];
if(amaxis==false)//更新第一步
{
amaxis=true;
amax=temp;
}else
if(temp>amax)//挑选最大点对值
amax=temp;
int temp2;//存储路径权值
//走的下一步对于最大点对值有利
if(c[i]<b[i].value+c[b[i].father])//i->i.father可走
temp2=b[i].value+c[b[i].father];
if(c[b[i].father]<b[i].value+c[i])//i.father->i可走
c[b[i].father]=b[i].value+c[i];
c[i]=temp2;//将起点->i的最大路径值存到c[i]
}
cout<<amax<<endl;
}
}