D. Almost Acyclic Graph【拓扑排序判环】

D. Almost Acyclic Graph time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output

You are given a directed graph consisting of n vertices and m edges (each edge is directed, so it can be traversed in only one direction). You are allowed to remove at most one edge from it.

Can you make this graph acyclic by removing at most one edge from it? A directed graph is called acyclic iff it doesn’t contain any cycle (a non-empty path that starts and ends in the same vertex).

Input

The first line contains two integers n and m (2 ≤ n ≤ 5001 ≤ m ≤ min(n(n - 1), 100000)) — the number of vertices and the number of edges, respectively.

Then m lines follow. Each line contains two integers u and v denoting a directed edge going from vertex u to vertex v (1 ≤ u, v ≤ nu ≠ v). Each ordered pair (u, v) is listed at most once (there is at most one directed edge from u to v).

Output

If it is possible to make this graph acyclic by removing at most one edge, print YES. Otherwise, print NO.

Examples input

3 4
1 2
2 3
3 2
3 1

output

YES

input

5 6
1 2
2 3
3 2
3 1
2 1
4 5

output

NO

Note

In the first example you can remove edge 《D. Almost Acyclic Graph【拓扑排序判环】》, and the graph becomes acyclic.

In the second example you have to remove at least two edges (for example, 《D. Almost Acyclic Graph【拓扑排序判环】》 and 《D. Almost Acyclic Graph【拓扑排序判环】》) in order to make the graph acyclic.

题意:判断去掉一条边,有向图是否存在环。

思路:直接用dfs判断环会超时。于是可以利用拓扑排序的思想,记录所有节点的入度。删除边时只需要将终点的入度-1就可以了,于是只需要一层循环枚举每个节点就可以了。然后用拓扑排序判断是否存在环。

代码:

#include<stdio.h>
#include<string.h>
#include<algorithm>
#include<math.h>
#include<queue>
using namespace std;
int n,m,G[505][505],in[505],deg[505];
bool topo()
{
    queue<int> q;
    int cnt=0;
    for(int i=1;i<=n;i++)
        if(!in[i]) q.push(i),cnt++;
    while(!q.empty())
    {
        int top=q.front(); q.pop();
        for(int i=1;i<=n;i++)
        {
            if(G[top][i] && in[i])
            {
                in[i]--;
                if(!in[i]) q.push(i),cnt++;
            }
        }
    }
    return cnt==n;
}
int main()
{
    while(~scanf("%d%d",&n,&m))
    {
        int u,v,flag=0;
        memset(G,0,sizeof G);
        memset(deg,0,sizeof deg);
        for(int i=0;i<m;i++)
        {
            scanf("%d%d",&u,&v);
            G[u][v]=1;
            deg[v]++;
        }
        for(int i=1;i<=n;i++)
        {
            if(deg[i])
            {
                memcpy(in,deg,sizeof deg);
                in[i]--;
                if(topo())
                {
                    flag=1;
                    break;
                }
            }
        }
        if(flag) printf("YES\n");
        else printf("NO\n");
    }
    return 0;
}

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