【Codeforces 501C】Misha and Forest

【链接】 我是链接,点我呀:)
【题意】


给你一棵树
但是每个节点只告诉你出度个数
以及所有和它相连的点的异或和.
让你还原这棵树

【题解】


叶子节点的话,他所有节点的异或和就是它那唯一的一个爸爸
因此,弄个拓扑排序,从最下层一直往上面进行拓扑排序,每次找到它的爸爸之后,就将这个儿子删掉.让爸爸的出边递减。
同时更新爸爸的异或和,直到爸爸没有儿子为止(也变成叶子节点了)。
(如果某个时刻chu[x]==0,那么x肯定是根节点了,说明找边的工作结束了。)

【代码】

#include <bits/stdc++.h>
#define ll long long
using namespace std;
const int N = 1<<16;
const long long M = 15e6;

int n;
int chu[N+10],sum[N+10];
int tot = 0;
queue<int> dl;

int main(){
    ios::sync_with_stdio(0),cin.tie(0);
    cin >> n;
    for (int i = 0;i < n;i++){
        cin >> chu[i] >> sum[i];
        tot+=chu[i];
        if (chu[i]==1){
            dl.push(i);
        }
    }
    cout<<tot/2<<endl;
    while (!dl.empty()){
        int x = dl.front();dl.pop();
        if (chu[x]==0) continue;
        chu[x] = 0;
        int y = sum[x];
        cout<<x<<" "<<y<<endl;
        sum[y]^=x;
        chu[y]--;
        if (chu[y]==1){
            dl.push(y);
        }
    }
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/10633025.html