这叫树形DP吗。。?断开某条边 求剩下两颗树数权值和的差最小
dfs一遍 枚举边 查了n久 wa n次 dp数组没初始化。。
在poj上1A感觉应该挺爽
1 #include <iostream> 2 #include<cstdio> 3 #include<cstring> 4 #include<algorithm> 5 #include<stdlib.h> 6 using namespace std; 7 #define N 100010 8 #define M 1000010 9 #define LL long long 10 LL dp[M<<1],p[N]; 11 struct node 12 { 13 int u,v,next; 14 }ed[M<<1]; 15 int head[N],t,n,m; 16 void init() 17 { 18 t = 1; 19 memset(head,-1,sizeof(head)); 20 } 21 void add(int u,int v) 22 { 23 ed[t].u = u; 24 ed[t].v = v; 25 ed[t].next = head[u]; 26 head[u] = t++; 27 } 28 LL dfs(int pre,int u,int e) 29 { 30 int i; 31 LL sum=p[u]; 32 for(i = head[u] ; i != -1 ; i = ed[i].next) 33 { 34 int v = ed[i].v; 35 if(v==pre) 36 continue; 37 sum+=dfs(u,v,i); 38 } 39 dp[e] = sum; 40 return dp[e]; 41 } 42 int main() 43 { 44 int i,kk=0; 45 while(scanf("%d%d",&n,&m)!=EOF) 46 { 47 if(n==0&&m==0) 48 break; 49 init();kk++; 50 memset(dp,0,sizeof(dp)); 51 LL s=0; 52 for(i =1; i <= n; i++) 53 { 54 scanf("%lld",&p[i]); 55 s+=p[i]; 56 } 57 for(i = 1; i <= m ;i++) 58 { 59 int u,v; 60 scanf("%d%d",&u,&v); 61 add(u,v); 62 add(v,u); 63 } 64 dfs(-1,i,0); 65 LL ans = s,o; 66 for(i = 0 ; i < t ; i++) 67 { 68 if(s-dp[i]>dp[i]) 69 o = s-dp[i]-dp[i]; 70 else 71 o = dp[i]-(s-dp[i]); 72 if(o<ans) 73 ans = o; 74 } 75 printf("Case %d: ",kk); 76 printf("%lld\n",ans); 77 } 78 return 0; 79 }