Time Limit: 3000/1000 MS (Java/Others) Memory Limit: 65535/32768 K (Java/Others) Total Submission(s): 336 Accepted Submission(s): 92
思路:dp[u][trap][dir]最优值,起始节点,已经过的trap数,是入点还是出点。0 out 1 in
ans=max(dp[u][trapu][0]+dp[v][trapv][1],dp[u][trapu][1]+dp[v][trapv][0],dp[u][trapu][0]+dp[v][trapv][0])
注意trap==C
1 #include<iostream> 2 #include<cstring> 3 #include<cstdio> 4 #define FOR(i,n) for(int i=0;i<n;++i) 5 #define clr(f,z) memset(f,z,sizeof(f)) 6 using namespace std; 7 const int mm=5e4+9; 8 class Edge 9 { 10 public:int v,next; 11 }e[mm*2]; 12 class node 13 { 14 public:int trap,val; 15 }f[mm]; 16 int head[mm],edge; 17 bool vis[mm]; 18 int cas,n,C,ans,dp[mm][5][2]; 19 void data() 20 { 21 clr(head,-1);edge=0; 22 } 23 void add(int u,int v) 24 { 25 e[edge].v=v;e[edge].next=head[u];head[u]=edge++; 26 } 27 void DP(int u) 28 { 29 int v,trap;vis[u]=1; 30 trap=f[u].trap; 31 dp[u][trap][1]=dp[u][trap][0]=f[u].val; 32 for(int i=head[u];~i;i=e[i].next) 33 { 34 v=e[i].v; 35 if(vis[v])continue; 36 DP(v); 37 for(int j=0;j<=C;++j) 38 for(int k=0;k+j<=C;++k) 39 { 40 if(j!=C)///0 out if(j==C) stop at u can't reatch v 41 { 42 ans=max(ans,dp[u][j][0]+dp[v][k][1]); 43 } 44 if(k!=C)///1 in if(k==C) stop at v can't reatch u 45 { 46 ans=max(ans,dp[u][j][1]+dp[v][k][0]); 47 } 48 if(j+k<C) 49 { 50 ans=max(ans,dp[u][j][0]+dp[v][k][0]); 51 } 52 } 53 trap=f[u].trap; 54 for(int j=0;j<=C;++j) 55 { 56 dp[u][j+trap][0]=max(dp[u][j+trap][0],dp[v][j][0]+f[u].val); 57 } 58 for(int j=1;j<=C;++j)///1 in if(j==0) it's impossble to reatch u 59 { 60 dp[u][j+trap][1]=max(dp[u][j+trap][1],dp[v][j][1]+f[u].val); 61 } 62 } 63 } 64 int main() 65 { int a,b; 66 while(~scanf("%d",&cas)) 67 { 68 while(cas--) 69 { data(); 70 scanf("%d%d",&n,&C); 71 FOR(i,n) 72 scanf("%d%d",&f[i].val,&f[i].trap); 73 FOR(i,n-1) 74 { 75 scanf("%d%d",&a,&b);add(a,b);add(b,a); 76 } 77 clr(vis,0);clr(dp,0); 78 ans=0; 79 DP(0); 80 printf("%d\n",ans); 81 } 82 } 83 return 0; 84 }