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.
The first line contains integer n (1 ≤ n ≤ 216), the number of vertices in the graph.
The i-th of the next lines contains numbers degreei and si (0 ≤ degreei ≤ n - 1, 0 ≤ si < 216), separated by a space.
In the first line print number m, the number of edges of the graph.
Next print m lines, each containing two distinct numbers, a and b (0 ≤ a ≤ n - 1, 0 ≤ b ≤ n - 1), corresponding to edge (a, b).
Edges can be printed in any order; vertices of the edge can also be printed in any order.
3 2 3 1 0 1 0
2 1 0 2 0
2 1 1 1 0
1 0 1
The XOR sum of numbers is the result of bitwise adding numbers modulo 2. This operation exists in many modern programming languages. For example, in languages C++, Java and Python it is represented as "^", and in Pascal — as "xor".
分析:
做的时候看题目看了好久没有看懂是什么意思。。。没接触过这种类型的题目,特别是这句话: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).比赛中问了一下同桌,才知道这句话的意思是第二个值为与该点相连的顶点号相异或的结果。。。又涨见识了。比赛的时候写的代码超时了,时间复杂度是O(n^2),当时写出来就已经感觉不错了,交上去测试数据也过了,但是比赛之后想想,应该还是会超时的,果然在17个点就已经超时了。最后得到CAPOUIS的点拨,利用了队列,进行了一些小优化,然后就过了。具体见代码注释。
#include <iostream>
#include <string.h>
#include <cstring>
#include <string>
#include <algorithm>
#include <stack>
#include <queue>
#include <stdio.h>
#include <stdlib.h>
#include <cstdlib>
#include <cmath>
#include <math.h>
#include <vector>
#include <map>
#include <time.h>
#include <ctime>
#include <set>
using namespace std;
#define M 70000
typedef struct
{
int id;
int d;
int s;
} Node;
Node f[M];
queue <Node> que;
int main()
{
int n;
cin >> n;
Node node;
std::ios::sync_with_stdio(false);
int cnt = 0;
for (int i = 0; i < n; i++)
{
f[i].id = i;
scanf("%d%d", &f[i].d, &f[i].s);
if(f[i].d == 1)
{
node.id = i;
node.d = f[i].d;
node.s = f[i].s;
que.push(node); //将度为1的点push到队列中
}
cnt += f[i].d;
}
cout << cnt/2 << endl; //输出边数
while(!que.empty())
{
node = que.front();
que.pop();
if(f[node.id].d != 1) //如果该顶点的度数为1,才进入下面的操作,虽然每次都是将度数为1的顶点push到队列中,但是有可能因为两个度数为1的顶点恰好相连时,不进行这步操作,则会输出两次同样的边
continue;
printf("%d %d\n", node.id, node.s);
f[node.s].d --; //将连接顶点的度数减一
f[node.s].s = f[node.s].s ^ node.id; //进行异或操作
f[node.id].d --; //将该顶点的度数减一
if(f[node.s].d == 1) //如果为1则push进队列
que.push(f[node.s]);
}
return 0;
}