题意 给出一棵树 每个节点有权值 要求父节点和子节点不能同时取 求能够取得的最大值 简单的树状dp,却RE了两次,WA了一次....无语,直接上代码: #include<iostream> #include<cstdio> #include<algorithm> #include<memory.h> using namespace std; const int INF=6002; int n,dp[INF][2],NE,node[INF],root[INF]; int head[INF],vis[INF]; struct nod { int u,v,val,next; } Edge[INF*2]; void addEdge(int u,int v,int val) { Edge[NE].u=u; Edge[NE].v=v; Edge[NE].val=val; Edge[NE].next=head[u]; head[u]=NE++; } void dfs(int u,int fa) { int i,j; for(i=head[u]; i!=-1; i=Edge[i].next) { int r=Edge[i].v; if(r==fa) continue; if(vis[r]==1) continue; dfs(r,u); dp[u][0]+=max(0,max(dp[r][0],dp[r][1])); dp[u][1]+=(dp[r][0]>0?dp[r][0]:0); vis[r]=1; } } int main() { int i,j,l,k; while(scanf("%d",&n)!=EOF) { int ans=0; NE=0; memset(vis,0,sizeof(vis)); memset(head,-1,sizeof(head)); memset(root,0,sizeof(root)); memset(dp,0,sizeof(dp)); for(i=1; i<=n; i++) cin>>node[i],dp[i][1]=node[i]; while(scanf("%d%d",&l,&k),(l||k)) { addEdge(k,l,node[k]); // addEdge(l,k,node[l]); root[k]=1; //root[l]=1; } for(i=1; i<=n; i++) { if(root[i]) { dfs(i,0); ans=max(ans,max(dp[i][1],dp[i][0])); } } cout<<ans<<endl; } return 0; }