题目链接
题意有坑点,理解完题意之后就真的比较的好写了。
一开始的时候,以为是一个种类并查集来任意两个相邻的点只能取一个,最后在一棵树上求权值之差……
然后再反复的理解题意,终于明白了,主要还是看了讨论区,(大雾……
有N个点的树,边M恒等于N-1,然后求割去一条边,使得最后剩余的两棵子树权值差最小。
这成了一个简单的搜索求子树权值问题了,比较的好解决。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
//#include <unordered_map>
//#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f3f3f3f3f
#define eps 1e-8
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
#define MP(a, b) make_pair(a, b)
#define MAX_3(a, b, c) max(a, max(b, c))
#define Rabc(x) x > 0 ? x : -x
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 1e5 + 7;
int N, M, head[maxN], cnt;
struct Eddge
{
int nex, to;
Eddge(int a=-1, int b=0):nex(a), to(b) {}
}edge[maxN << 1];
inline void addEddge(int u, int v)
{
edge[cnt] = Eddge(head[u], v);
head[u] = cnt++;
}
inline void _add(int u, int v) { addEddge(u, v); addEddge(v, u); }
ll a[maxN], all, ans, siz[maxN];
void dfs(int u, int fa)
{
siz[u] = 0;
for(int i=head[u], v; ~i; i=edge[i].nex)
{
v = edge[i].to;
if(v == fa) continue;
dfs(v, u);
siz[u] += siz[v];
}
siz[u] += a[u];
ans = min(ans, Rabc((all - 2LL * siz[u])));
}
inline void init()
{
cnt = 0; all = 0; ans = INF;
for(int i=1; i<=N; i++) head[i] = -1;
}
int main()
{
int Cas = 0;
while(scanf("%d%d", &N, &M) && (N | M))
{
init();
for(int i=1; i<=N; i++) { scanf("%lld", &a[i]); all += a[i]; }
for(int i=1, u, v; i<=M; i++)
{
scanf("%d%d", &u, &v);
_add(u, v);
}
dfs(1, 0);
printf("Case %d: %lld\n", ++Cas, ans);
}
return 0;
}