洛谷 P2017 [USACO09DEC]晕牛Dizzy Cows

前言

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

题解

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

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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值