poj 3140 Contestants Division

http://poj.org/problem?id=3140

这道题数据大,需要用long long,dfs枚举删除的边求最小就行。

 1 #include <cstdio>
 2 #include <vector>
 3 #include <cstring>
 4 #include <algorithm>
 5 #define ll long long
 6 #define maxn 200000
 7 using namespace std;
 8 const ll inf=99999999999999999ll;
 9 
10 ll a[maxn];
11 ll total;
12 ll min1;
13 int n,m;
14 vector<int>q[maxn];
15 bool vis[maxn];
16 ll ABS(ll a)
17 {
18     if(a<0) return -a;
19     return a;
20 }
21 
22 ll min2(ll a,ll b)
23 {
24     if(a>b) return b;
25     return a;
26 }
27 
28 ll dfs(int num)
29 {
30     vis[num]=true;
31     ll ans=a[num];
32     for(int i=0; i<(int)q[num].size(); i++)
33     {
34         int to=q[num][i];
35         if(!vis[to])
36         {
37           ans+=dfs(to);
38         }
39     }
40     min1=min2(min1,ABS(total-ans-ans));
41     return ans;
42 }
43 
44 int main()
45 {
46     int case1=0;
47     while(scanf("%d%d",&n,&m)!=EOF)
48     {
49         min1=inf;
50         if(n==0&&m==0) break;
51         memset(a,0,sizeof(a));
52         memset(vis,false,sizeof(vis));
53         total=0;
54         for(int i=0; i<=n; i++)
55         {
56             q[i].clear();
57         }
58         for(int i=1; i<=n; i++)
59         {
60             scanf("%lld",&a[i]);
61             total+=a[i];
62         }
63         for(int i=1; i<=m; i++)
64         {
65             int x,y;
66             scanf("%d%d",&x,&y);
67             q[x].push_back(y);
68             q[y].push_back(x);
69         }
70         dfs(1);
71         printf("Case %d: %lld\n",++case1,min1);
72     }
73     return 0;
74 }
View Code

 

posted @ 2014-07-04 15:06  null1019  阅读(157)  评论(0编辑  收藏  举报