洛谷 P2017 [USACO09DEC]晕牛Dizzy Cows

来源:互联网 发布:网络犯罪调查第二季 编辑:程序博客网 时间:2024/06/05 13:44

前言

这么简单的一道题我居然没有想出来
不知道是我太困了还是我太菜了

题解

对于已经输入的边,我们进行拓扑排序,然后给他编号
然后根据拓扑排序,只要有环,那么就一定有一个可信的顺序
于是你对于加入的每一条边,就让他拓扑编号小的连向拓扑编号大的就可以了
这样你就可以保证你的图是由一个可行的拓扑序了

CODE:

#include<cstdio>#include<iostream>#include<algorithm>#include<cstring>#include<queue>using namespace std;const int N=100005;int n,m1,m2;struct qq{    int x,y,last;}e[N];int num,last[N];int d[N];void init (int x,int y){    d[y]++;    num++;    e[num].x=x;e[num].y=y;    e[num].last=last[x];    last[x]=num;}int vis[N];//访问顺序 queue<int> q;void topsort (){    int cnt=0;    for (int u=1;u<=n;u++)        if (d[u]==0)            q.push(u);    while (!q.empty())    {        int x=q.front();q.pop();vis[x]=++cnt;        for (int u=last[x];u!=-1;u=e[u].last)        {            int y=e[u].y;            d[y]--;            if (d[y]==0) q.push(y);        }    }}int main(){    num=0;memset(last,-1,sizeof(last));    scanf("%d%d%d",&n,&m1,&m2);    for (int u=1;u<=m1;u++)    {        int x,y;        scanf("%d%d",&x,&y);        init(x,y);    }    topsort();    for (int u=1;u<=m2;u++)    {        int x,y;        scanf("%d%d",&x,&y);        if (vis[x]<vis[y]) printf("%d %d\n",x,y);        else printf("%d %d\n",y,x);    }    return 0;}
原创粉丝点击