Educational Codeforces Round 36 (Rated for Div. 2) D. Almost Acyclic Graph

该博客讨论了一种有向图的问题,即在给定的有向图中,判断是否能通过删除一条边使得图中不出现环。博主提出了使用拓扑排序的方法来解决,首先尝试直接进行拓扑排序,若成功则图原本无环,输出YES;若存在环,则枚举度数为1的节点的出边,再次尝试拓扑排序,找到能消除环的边。代码使用C++实现,通过优化减少了枚举次数,提高了效率。
摘要由CSDN通过智能技术生成

题目大意

给出一个 n n n个点, m m m条边的有向图,
问是否可以再删除一条边之后,图中不会出现环。

时间限制

1s

数据范围

n ≤ 500 n\le500 n500
m ≤ 1 0 5 m\le10^5 m105

题解

判断有向无环图,最简单的方法就是拓扑排序
每一次拓扑排序的时间复杂度是 O ( m ) O\pod{m} O(m),显然不能直接枚举删除哪条边。
不过,可以发现,有些便无论是否被删除它都不会对答案造成影响,比如说本身就不在环里面的边。

先进行一次拓扑排序,如果没有环,就直接输出YES,如果有环,那么图中必然还会剩余一些边,
那么就枚举这些边中连进点度数为 1 1 1的边。
这样枚举的边就明显减少,可以通过此题。

Code

//#pragma GCC optimize (2)
//#pragma G++ optimize (2)
#include <cstdio>
#include <algorithm>
#include <cstring>
#include <cmath>
#include <iostream>
#include <vector>
#include <queue>
#define G getchar
#define ll long long
using namespace std;

ll read()
{
    char ch;
    for(ch = G();(ch < '0' || ch > '9') && ch != '-';ch = G());
    ll n = 0 , w;
    if (ch == '-')
    {
        w = -1;
        ch = G();
    } else w = 1;
    for(;'0' <= ch && ch <= '9';ch = G())n = (n<<1)+(n<<3)+ch-48;
    return n * w;
}

const int N = 100003;
int n , m , x , y , cnt;
int nxt[N] , lst[N] , to[N] , tot;
int xx , yy;
int l , r , q[N];
int d[503] , g[503];
bool ans , bz[503];

void ins (int x , int y)
{
    tot++;
    d[y]++;
    to[tot] = y;
    nxt[tot] = lst[x];
    lst[x] = tot;
}

bool bfs()
{
    l = 0;
    r = 0;
    memcpy(g , d , sizeof(g));
    g[yy]--;
    for (int i = 1 ; i <= n; i++)
        if (g[i] == 0)
        {
            r++;
            q[r] = i;
        }

    for ( ; l < r ; )
    {
        l++;
        x = q[l];
        for (int i = lst[x] ; i ; i = nxt[i])
            if (x != xx || to[i] != yy)
            {
                g[to[i]]--;
                if (g[to[i]] == 0)
                {
                    r++;
                    q[r] = to[i];
                }
            }
    }
    return (l == n);
}

int main()
{
    //freopen("d.in","r",stdin);
    //freopen("d.out","w",stdout);

    n = read();
    m = read();
    for (int i = 0 ; i < m ; i++)
    {
        x = read();
        y = read();
        ins(x , y);
    }

    memset(bz , 0 , sizeof(bz));
    ans = bfs();
    for (int i = 1 ; i <= n ; i ++)
        if (g[i] == 1) bz[i] = 1;
    for (int i = 1 ; i <= n ; i ++)
    {
        xx = i;
        for (int j = lst[i] ; j ; j = nxt[j])
        {
            yy = to[j];
            if (bz[yy] && bfs())
            {
                ans = 1;
                break;
            }
        }
        if (ans) break;
    }

    if (ans) puts("YES"); else puts("NO");

    return 0;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值