Description
Input
Output
Sample Input
5 1 1 2 1 3 1 1 1
Sample Output
3 2 3 44
求一颗树上离某点最远的距离
我们先求从改点往下走最远能走多远
然后再求从这点往上最远能走多远
因为会出现从这点往上又往下走
只保存最大距离的话会出现从该点出发又回到该点的情况
所以要保存某点向下的最大距离和次大距离
ACcode:
#pragma warning(disable:4786)//使命名长度不受限制 #pragma comment(linker, "/STACK:102400000,102400000")//手工开栈 #include <map> #include <set> #include <queue> #include <cmath> #include <stack> #include <cctype> #include <cstdio> #include <cstring> #include <stdlib.h> #include <iostream> #include <algorithm> #define rd(x) scanf("%d",&x) #define rd2(x,y) scanf("%d%d",&x,&y) #define rd3(x,y,z) scanf("%d%d%d,&x,&y,&z) #define rdl(x) scanf("%I64d,&x); #define rds(x) scanf("%s",x) #define rdc(x) scanf("%c",&x) #define ll long long int #define ull unsigned long long #define maxn 10005 #define mod 1000000007 #define INF 0x3f3f3f3f //int 最大值 #define FOR(i,f_start,f_end) for(int i=f_start;i<=f_end;++i) #define MT(x,i) memset(x,i,sizeof(x)) #define PI acos(-1.0) #define E exp(1) #define eps 1e-8 ll gcd(ll a,ll b){return b==0?a:gcd(b,a%b);} ll mul(ll a,ll b,ll p){ll sum=0;for(;b;a=(a+a)%p,b>>=1)if(b&1)sum=(sum+a)%p;return sum;} inline void Scan(int &x) { char c;while((c=getchar())<'0' || c>'9');x=c-'0'; while((c=getchar())>='0' && c<='9') x=(x<<3)+(x<<1)+c-'0'; } using namespace std; struct tree{ int to,next; int data; }my[maxn]; int head[maxn],tot; int dp[maxn][3]; void init(){memset(head,-1,sizeof(head));tot=0;memset(dp,0,sizeof(dp));} void add(int u,int v,int data){ my[tot].to=v;my[tot].next=head[u]; my[tot].data=data;head[u]=tot++; } void fun1(int st){ int biggest=0,bigger=0,tmp=0; for(int i=head[st];i!=-1;i=my[i].next){ int v=my[i].to; fun1(v); tmp=dp[v][0]+my[i].data; if(biggest<=tmp){ bigger=biggest; biggest=tmp; }else if(bigger<tmp) bigger=tmp; } dp[st][0]=biggest; dp[st][1]=bigger; } void fun2(int st){ for(int i=head[st];i!=-1;i=my[i].next){ int v=my[i].to; dp[v][2]=max(dp[st][2],dp[v][0]+my[i].data==dp[st][0]?dp[st][1]:dp[st][0])+my[i].data; fun2(v); } } int main(){ int n,loop,cnt=1; while(~rd(n)){ int v,data; init(); FOR(i,2,n){ rd2(v,data); add(v,i,data); } fun1(1);fun2(1); FOR(i,1,n)printf("%d\n",max(dp[i][0],dp[i][2])); } return 0; }