对每棵树做DP,有环特判即可。。
DP方程居然写错了。。。
1 #include<bits/stdc++.h> 2 #define inc(i,l,r) for(i=l;i<=r;i++) 3 #define dec(i,l,r) for(i=l;i>=r;i--) 4 #define mem(a) memset(a,0,sizeof(a)) 5 #define inf 1e9 6 #define ll long long 7 #define succ(x) (1<<x) 8 #define NM 1000000+5 9 using namespace std; 10 int read(){ 11 int x=0,f=1;char ch=getchar(); 12 while(!isdigit(ch)){if(ch=='-')f=-1;ch=getchar();} 13 while(isdigit(ch))x=x*10+ch-'0',ch=getchar(); 14 return x*f; 15 } 16 struct edge{ 17 int t,v; 18 edge *next; 19 }e[2*NM],*h[NM]; 20 int a[NM],f[NM],i,n,s,X,Y,t; 21 ll ans,d[NM],g[NM],_x,_y; 22 bool v[NM],V[NM]; 23 void add(int x,int y){ 24 e[++s].t=y;e[s].next=h[x];h[x]=e+s; 25 } 26 void dfs(int x,int k){ 27 v[x]++;V[x]=true; 28 for(edge *j=h[x];j;j=j->next) 29 if(j->t!=k){ 30 if(X==0&&v[j->t]){ 31 X=x;Y=j->t; 32 } 33 if(!v[j->t]){ 34 dfs(j->t,x); 35 g[x]+=max(d[j->t],g[j->t]); 36 d[x]+=g[j->t]; 37 } 38 } 39 if(x!=X)d[x]+=a[x]; 40 } 41 int main(){ 42 n=read(); 43 inc(i,1,n)f[i]=i; 44 inc(i,1,n){ 45 a[i]=read();t=read(); 46 add(i,t);add(t,i); 47 } 48 inc(i,1,n) 49 if(!V[i]){ 50 X=0; 51 mem(d);mem(g);mem(v); 52 dfs(i,0); 53 _x=d[i];_y=g[i]; 54 mem(d);mem(g);mem(v); 55 X=Y; 56 dfs(i,0); 57 _x=max(_x,d[i]);_y=max(_y,g[i]); 58 ans+=max(_x,_y); 59 } 60 printf("%lld\n",ans); 61 return 0; 62 }