[Ahoi2013]连通图 && DZY Loves Chinese II 线性基

Description
给你一张无向图,每次删掉若干条边,问这个图是否仍然联通,每个询问之间独立。


Sample Input
5 10
2 1
3 2
4 2
5 1
5 3
4 1
4 3
5 2
3 1
5 4
5
1 1
3 7 0 3
4 0 7 4 6
2 2 7
4 5 0 2 13


Sample Output
Connected
Connected
Connected
Connected
Disconnected


很久以前就A了这题的弟弟题了,现在回来做,这题真是神啊。
考虑一个图不连通,会出现什么。
假设我们构成一个dfs树,一条树边,以及所有覆盖它的非树边如果都被删除了,那么这个图就不连通了。
根据这个我们可以搞点东西。
对于非树边,我们随机一个值,对于树边,将所有覆盖它的非树边异或起来得到它的权值。
那么对于给出来的边,每次做一个线性基,判一下异或起来能否为0。


#include <ctime>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <algorithm>

using namespace std;
typedef long long LL;
int _max(int x, int y) {return x > y ? x : y;}
int _min(int x, int y) {return x < y ? x : y;}
int read() {
	int s = 0, f = 1; char ch = getchar();
	while(ch < '0' || ch > '9') {if(ch == '-') f = -1; ch = getchar();}
	while(ch >= '0' && ch <= '9') s = s * 10 + ch - '0', ch = getchar();
	return s * f;
}

struct edge {
	int x, y, next;
} e[1000010]; int len, last[100010];
int c[500010], gg[100010];
bool v[1000010];
int f[100010];
int bin[31];
int s[20];

void ins(int x, int y) {
	e[++len].x = x, e[len].y = y;
	e[len].next = last[x], last[x] = len;
}

int findfa(int x) {
	if(f[x] != x) f[x] = findfa(f[x]);
	return f[x];
}

void dfs(int x, int fa) {
	for(int k = last[x]; k; k = e[k].next) if(!v[k]){
		int y = e[k].y;
		if(y != fa) dfs(y, x);
	}
}

int getxor(int x, int fa) {
	int s = gg[x];
	for(int k = last[x]; k; k = e[k].next) if(!v[k]){
		int y = e[k].y;
		if(y != fa) {
			c[k / 2] = getxor(y, x);
			s ^= c[k / 2];
		}
	} return s;
}

bool check() {
	int tot = 0;
	for(int i = 30; i >= 0; i--) {
		for(int j = ++tot; j <= s[0]; j++) if(s[j] & bin[i]){
			swap(s[j], s[tot]); break;
		} if(!(s[tot] & bin[i])) {tot--; continue;}
		for(int j = 1; j <= s[0]; j++) if(j != tot && (s[j] & bin[i])) s[j] ^= s[tot];
	} if(tot == s[0]) return 1;
	return 0;
}

int main() {
	srand(time(0));
	bin[0] = 1; for(int i = 1; i <= 30; i++) bin[i] = bin[i - 1] * 2;
	int n = read(), m = read(); len = 1;
	for(int i = 1; i <= m; i++) {
		int x = read(), y = read();
		ins(x, y), ins(y, x);
	} for(int i = 1; i <= n; i++) f[i] = i;
	for(int i = 2; i <= len; i += 2) {
		int fx = findfa(e[i].x), fy = findfa(e[i].y);
		if(fx != fy) f[fx] = fy;
		else v[i] = v[i + 1] = 1, c[i / 2] = rand() * rand();
	} dfs(1, 0);
	for(int i = 2; i <= len; i += 2) if(v[i]){
		int x = e[i].x, y = e[i].y;
		gg[x] ^= c[i / 2], gg[y] ^= c[i / 2];
	} getxor(1, 0);
	int q = read();
	int sum = 0;
	for(int i = 1; i <= q; i++) {
		memset(s, 0, sizeof(s));
		s[0] = read();
		for(int j = 1; j <= s[0]; j++) s[j] = c[read() ^ sum];
		if(check()) ++sum, puts("Connected");
		else puts("Disconnected");
	}
	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值