CodeForces 501C (拓扑排序,思维)

题意:
给出n个点的森林,编号从0到n-1,给定每个点的度数及该点相邻点的编号异或和,还原出这个森林。

思路:
关键点在度数为1的节点,就是叶子,叶子的相邻点只有一个,异或和即为相邻点的编号,把这些边补全之后,另一些被叶子连接的点也能够确认下一条边,直到所有边都被确定。

代码:

#include <iostream>
#include <iomanip>
#include <algorithm>
#include <cstring>
#include <cctype>
#include <cstdlib>
#include <cstdio>
#include <cmath>
#include <ctime>
#include <map>
#include <list>
#include <set>
#include <stack>
#include <queue>
#include <string>
#include <sstream>
#define pb push_back
#define X first
#define Y second
#define ALL(x) x.begin(),x.end()
#define INS(x) inserter(x,x.begin())
#define pii pair<int,int>
#define qclear(a) while(!a.empty())a.pop();
#define lowbit(x) (x&-x)
#define sd(n) scanf("%d",&n)
#define sdd(n,m) scanf("%d%d",&n,&m)
#define sddd(n,m,k) scanf("%d%d%d",&n,&m,&k)
#define mst(a,b) memset(a,b,sizeof(a))
#define cout3(x,y,z) cout<<x<<" "<<y<<" "<<z<<endl
#define cout2(x,y) cout<<x<<" "<<y<<endl
#define cout1(x) cout<<x<<endl
#define IOS std::ios::sync_with_stdio(false)
#define SRAND srand((unsigned int)(time(0)))
typedef long long ll;
typedef unsigned long long ull;
typedef unsigned int uint;
using namespace std;
const double PI=acos(-1.0);
const int INF=0x3f3f3f3f;
const ll mod=1000000007;
const double eps=1e-8;
const int maxn=65536+10;
const int maxm=10005;

int n;
int deg[maxn];
int xors[maxn];
vector<int>maps[maxn];
void solve() {
    sd(n);
    for(int i=0;i<n;i++){
        sdd(deg[i],xors[i]);
    }
    queue<int>que;
    for(int i=0;i<n;i++){
        if(deg[i]==1)que.push(i);
    }
    int m=0;
    while(!que.empty()){
        int u=que.front();que.pop();
        if(deg[u]==0)continue;
        int v=xors[u];
        maps[u].pb(v);
        deg[v]--;
        deg[u]--;
        m++;
        xors[v]^=u;
        if(deg[v]==1)que.push(v);
    }
    printf("%d\n",m);
    for(int i=0;i<n;i++){
        for(int j=0;j<maps[i].size();j++){
            printf("%d %d\n",i,maps[i][j]);
        }
    }
    return ;
}
int main() {
#ifdef LOCAL
    freopen("in.txt","r",stdin);
//    freopen("out.txt","w",stdout);
#else
    //    freopen("","r",stdin);
    //    freopen("","w",stdout);
#endif
    solve();
    return 0;
}

 

    原文作者:拓扑排序
    原文地址: https://blog.csdn.net/weixin_38378637/article/details/81146316
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞