树形结构+拓扑思维 Codeforces Round #285 (Div. 2) C题 Misha and Forest

Misha and Forest

Let’s define a forest as a non-directed acyclic graph (also without loops and parallel edges). One day Misha played with the forest consisting of n vertices. For each vertex v from 0 to n - 1 he wrote down two integers, degreev and sv, were the first integer is the number of vertices adjacent to vertex v, and the second integer is the XOR sum of the numbers of vertices adjacent to v (if there were no adjacent vertices, he wrote down 0).

Next day Misha couldn’t remember what graph he initially had. Misha has values degreev and sv left, though. Help him find the number of edges and the edges of the initial graph. It is guaranteed that there exists a forest that corresponds to the numbers written by Misha.


题目大意:n 个点,每个点都有两个表示关系,degreev 和 sv, 分别代表这个点的度数和与这个点相连的点异或值和;让你构造一张无向无环图(就是树)满足这些条件;

构造题终归是比较难的;

可以发现,叶子结点只有一个度,并且与它连接的点的异或值和值 sv 一定是它的父节点;

发现这个,这题就可以套用拓扑排序的思路了,每次找出 degreev 等于1的点,入队,然后扩展;

代码:

#include<bits/stdc++.h>
#define LL long long
#define pa pair<int,int>
#define ls k<<1
#define rs k<<1|1
#define inf 0x3f3f3f3f
using namespace std;
const int N=100100;
const int M=2000100;
const LL mod=1e9+7;
int s[N],d[N];
queue<int>qu;
vector<pa>ans;
void bfs(){
	while(!qu.empty()){
		int p=qu.front();
		qu.pop();
		if(d[p]==1){//这个特别注意 
			ans.push_back(pa(p,s[p]));
			d[s[p]]--,s[s[p]]^=p;
			if(d[s[p]]==1) qu.push(s[p]);
		}
	}
}
int main(){
	int n;scanf("%d",&n);
	for(int i=0;i<n;i++) scanf("%d%d",&d[i],&s[i]);
	for(int i=0;i<n;i++){
		if(d[i]==1) qu.push(i);
	}
	bfs();
	printf("%d\n",(int)ans.size());
	for(int i=0;i<(int)ans.size();i++) printf("%d %d\n",ans[i].first,ans[i].second);
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值