【SPOJ-PONY1】Help Dr Whooves【prufer序列】

http://www.spoj.com/problems/PONY1/

题意:

给出一个n个点m条边的图,问添加最少的边把这个图补成连通图的方案数


用prufer序列的推论,答案为

(Π 联通块大小) * 点数 ^ (联通块个数 - 2)


/* Footprints In The Blood Soaked Snow */
#include <cstdio>
#include <algorithm>

using namespace std;

typedef unsigned long long ULL;

const int maxn = 1000005, maxm = 100005, maxq = maxn;
const ULL p = 999999937;

int n, m, head[maxn], cnt, size[maxn], tot, q[maxq];
bool vis[maxn];

struct _edge {
	int v, next;
} g[maxm << 1];

inline int iread() {
	int f = 1, x = 0; char ch = getchar();
	for(; ch < '0' || ch > '9'; ch = getchar()) f = ch == '-' ? -1 : 1;
	for(; ch >= '0' && ch <= '9'; ch = getchar()) x = x * 10 + ch - '0';
	return f * x;
}

inline void add(int u, int v) {
	g[cnt] = (_edge){v, head[u]};
	head[u] = cnt++;
}

inline void bfs(int x) {
	int h = 0, t = 0;
	size[++tot] = vis[q[t++] = x] = 1;
	while(h != t) {
		int u = q[h++];
		for(int i = head[u]; ~i; i = g[i].next)
			if(!vis[g[i].v]) {
				size[tot]++;
				vis[q[t++] = g[i].v] = 1;
			}
	}
}

inline ULL qpow(ULL x, ULL n) {
	ULL ans = 1;
	for(ULL t = x; n; n >>= 1, t = t * t % p) if(n & 1) ans = ans * t % p;
	return ans;
}

int main() {
	int T = iread();
	while(T--) {
		n = iread(); m = iread();
		for(int i = 1; i <= n; i++) size[i] = vis[i] = 0, head[i] = -1; cnt = tot = 0;

		for(int i = 1; i <= m; i++) {
			int x = iread(), y = iread();
			add(x, y); add(y, x);
		}

		for(int i = 1; i <= n; i++) if(!vis[i]) bfs(i);

		ULL ans = 1;
		if(tot > 1) {
			for(int i = 1; i <= tot; i++) ans = ans * size[i] % p;
			ans = ans * qpow(n, tot - 2) % p;
		}

		printf("%llu\n", ans);
	}
	return 0;
}


你可能感兴趣的:(prufer)