1. 程式人生 > >D. Almost Acyclic Graph【拓撲排序判環】

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 , and the graph becomes acyclic.

In the second example you have to remove at least two edges (for example,  and ) 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;
}