Codeforces Round #285 (Div. 2) C. Misha and Forest 构造

思路:无向无环图中边的条数不超过n - 1,故一定存在叶子节点。由于叶子节点的邻边可直接确定,可以直接输出。将叶子节点所在边移除,迭代处理所有的叶子节点,直到所有节点都处理完毕。

代码如下:

#include <cstdio>
using namespace std;
#define N (1u << 16)
int deg[N], sum[N], leaves[N], edge[N][2];

int main(){
	int n, cnt = 0, ans = 0;
	scanf("%d", &n);
	for(int i = 0; i < n; ++i){
		scanf("%d %d", °[i], &sum[i]);
		if(deg[i] == 1)
			leaves[cnt ++] = i;
	}
	for(int i = 0; i < cnt; ++i){
		int u = leaves[i], v = sum[u];
        if(!deg[u])
            continue;
		edge[ans][0] = u, edge[ans][1] = v;
		ans ++;
		sum[v] ^= u;
		if(--deg[v] == 1)
			leaves[cnt ++] = v;
	}
	printf("%d\n", ans);
	for(int i = 0; i < ans; ++i)
        printf("%d %d\n", edge[i][0], edge[i][1]);
	return 0;
}


你可能感兴趣的:(codeforces,构造)