当前位置: 代码迷 >> 综合 >> Contestants Division(树形dp+删边)
  详细解决方案

Contestants Division(树形dp+删边)

热度:44   发布时间:2024-01-12 14:19:19.0

题目:Contestants Division

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 s, t, 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


题意:

给一个n个结点的树,每个节点上有一个值,表示k个学生,然后求删除一条边后分成的两个子树的学生数差最小,输出得到的差值。

输入:

第一个n表示n个结点,第二行表示每个节点有的学生数,后面就是描述树。

思路:这个题没有用dp数组,搜索的时候有返回值。

搜索枚举所有的边,然后选择删掉的边。

需要注意的一点,long long 取绝对值不能使用abs()函数,只能比较进行交换。

源代码:

#include <iostream>
#include <stdio.h>
#include <cstring>
#include <algorithm>
#include <cmath>
#include <iomanip>
#include <vector>
#define maxn 100005
typedef long long ll;
using namespace std;
ll n,m;
vector <ll> tree[maxn];
ll sum,ans;
ll v[maxn];
ll tree_dp(ll now,ll pre){ll num = 0;for (int i = 0; i < tree[now].size(); i++){if (tree[now][i] == pre)continue;ll temp = tree_dp(tree[now][i],now);num += temp;if (sum-temp*2>=0)ans = min(ans,sum-temp*2);elseans = min(ans,temp*2-sum);}return num + v[now];
}
int main(){int flag = 0;while (scanf("%lld%lld",&n,&m)!=EOF){if (n == 0 && m == 0)break;sum = 0;ans = 9999999999999;for (int i = 0; i <= n; i++)tree[i].clear();int x,y;for (int i = 1; i <= n; i++){scanf("%lld",&v[i]);sum += v[i];}for (int i = 1; i <= m; i++){scanf("%d%d",&x,&y);tree[x].push_back(y);tree[y].push_back(x);}tree_dp(1,0);if (n == 1){printf("Case %d: %lld\n",++flag,v[1]);continue;}printf("Case %d: %lld\n",++flag,ans);}return 0;
}