CF 915 D 拓扑排序

#include <bits/stdc++.h>

using namespace std;

const int maxn = 1e5 + 10;
const int mod = 142857;
int t,n,m,k,x,u,v,w,num,flag;
vector<int> G[maxn];
int inDeg[maxn], ruDeg[maxn];
int virus[maxn];
queue<int> q;

bool topSort()
{
    num=0;
    while(!q.empty()) q.pop();
    for(int i=1;i<=n;i++) if(!inDeg[i]) q.push(i);
    while(!q.empty())
    {
        int now = q.front();
        q.pop();
        num++;
        for(int i=0;i<G[now].size();i++)
        {
            int nxt = G[now][i];
            if(--inDeg[nxt] == 0) q.push(nxt);
        }
    }
    if(num == n) return true;
    else return false;
}

int main()
{
       while(~ scanf("%d%d",&n,&m) )
       {
            memset(inDeg,0,sizeof(inDeg));
            memset(ruDeg,0,sizeof(ruDeg));
            for(int i=1;i<=n;i++) G[i].clear();
            while(m--)
            {
                scanf("%d%d",&u,&v);
                G[u].push_back(v);
                inDeg[v]++;
                ruDeg[v]++;
            }
            if(topSort())
            {
                puts("YES");
                continue;
            }
            else
            {
                flag = 0;
                for(int i=1; i<=n; i++)
                {
                    memcpy(inDeg,ruDeg,sizeof(ruDeg));
                    if(inDeg[i] >= 1)
                    {
                        inDeg[i]--;
                        if(topSort())
                        {
                            flag = 1;
                            puts("YES");
                            break;
                        }
                    }
                }
            }
            if(flag == 0) puts("NO");
       }
}
posted @ 2018-06-13 00:52  Roni_i  阅读(208)  评论(0编辑  收藏  举报