POJ 3140 Contestants Division(树上DFS)

题目链接:http://poj.org/problem?id=3140

题目:

Description

In the new ACM-ICPC Regional Contest, a special monitoring and submitting system will be set up, and students will be able to compete at their own universities. However there’s one problem. Due to the high cost of the new judging system, the organizing committee can only afford to set the system up such that there will be only one way to transfer information from one university to another without passing the same university twice. The contestants will be divided into two connected regions, and the difference between the total numbers of students from two regions should be minimized. Can you help the juries to find the minimum difference?

Input

There are multiple test cases in the input file. Each test case starts with two integers N and M, (1 ≤ N ≤ 100000, 1 ≤ M ≤ 1000000), the number of universities and the number of direct communication line set up by the committee, respectively. Universities are numbered from 1 to N. The next line has N integers, the Kth integer is equal to the number of students in university numbered K. The number of students in any university does not exceed 100000000. Each of the following M lines has two integers st, and describes a communication line connecting university s and university t. All communication lines of this new system are bidirectional.

N = 0, M = 0 indicates the end of input and should not be processed by your program.

Output

For every test case, output one integer, the minimum absolute difference of students between two regions in the format as indicated in the sample output.

Sample Input

7 6
1 1 1 1 1 1 1
1 2
2 7
3 7
4 6
6 2
5 7
0 0

Sample Output

Case 1: 1

Source

题意:给定一棵树,每个顶点上都有值,去掉一条边,剩下的两棵树,要使得两棵树的权值差最小。

题解:DFS跑跑

 1 #include <vector>
 2 #include <cstdio>
 3 #include <cstring>
 4 #include <iostream>
 5 #include <algorithm>
 6 using namespace std;
 7 
 8 typedef long long LL;
 9 const int N=100000+10;
10 vector <int> E[N];
11 LL a[N],sum,dp[N],ans;
12 
13 void init(){
14     sum=0;
15     ans=1e18;
16     memset(dp,0,sizeof(dp));
17     for(int i=0;i<N;i++) E[i].clear();
18 }
19 
20 void DFS(int u,int Fa){
21     dp[u]=a[u];
22     for(int i=0;i<E[u].size();i++){
23         int v=E[u][i];
24         if(v==Fa) continue;
25         DFS(v,u);
26         dp[u]+=dp[v];
27     }
28     if(u!=1) ans=min(ans,llabs(sum-2*dp[u]));
29 }
30 
31 int main(){
32     int n,m,Case=1;
33     while(scanf("%d%d",&n,&m)!=EOF){
34         if(n==0&&m==0) break;
35         init();
36         for(int i=1;i<=n;i++){
37             scanf("%lld",&a[i]);
38             sum+=a[i];
39         }
40         for(int i=1;i<=m;i++){
41             int u,v;
42             scanf("%d%d",&u,&v);
43             E[u].push_back(v);
44             E[v].push_back(u);
45         }
46         DFS(1,0);
47         printf("Case %d: %lld\n",Case++,ans);
48     }
49     return 0;
50 }

猜你喜欢

转载自www.cnblogs.com/Leonard-/p/8910059.html