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;
}