zoukankan      html  css  js  c++  java
  • HDU 3342 Legal or Not

    有向图判环。

    拓扑排序

    判断拓扑排序的结果是否包含(n)个点。

    const int N=110;
    vector<int> g[N];
    int din[N];
    int n,m;
    
    bool topo()
    {
        queue<int> q;
        for(int i=0;i<n;i++)
            if(din[i] == 0)
                q.push(i);
    
        int cnt=0;
        while(q.size())
        {
            int t=q.front();
            q.pop();
            cnt++;
    
            for(int i=0;i<g[t].size();i++)
            {
                int j=g[t][i];
                if(--din[j] == 0) q.push(j);
            }
        }
        if(cnt < n) return false;
        return true;
    }
    
    int main()
    {
        while(cin>>n>>m && n)
        {
            for(int i=0;i<n;i++) g[i].clear(),din[i]=0;
    
            while(m--)
            {
                int a,b;
                cin>>a>>b;
                g[a].pb(b);
                din[b]++;
            }
    
            if(topo()) puts("YES");
            else puts("NO");
        }
    
        //system("pause");
        return 0;
    }
    

    DFS判环

    需要回溯,从第(i)个节点为起点,判环完成后要将已访问结点的标记清除,若不清除,会对以其他点为起点的判环过程产生影响。

    const int N=110;
    vector<int> g[N];
    bool vis[N];
    int n,m;
    
    bool dfs(int u)
    {
        if(vis[u]) return false;
        vis[u]=true;
        for(int i=0;i<g[u].size();i++)
        {
            int j=g[u][i];
            if(!dfs(j)) return false;
        }
        vis[u]=false;
        return true;
    }
    
    int main()
    {
        while(cin>>n>>m && n)
        {
            for(int i=0;i<n;i++) g[i].clear(),vis[i]=0;
    
            while(m--)
            {
                int a,b;
                cin>>a>>b;
                g[a].pb(b);
            }
    
            bool ok=true;
            for(int i=0;i<n;i++)
                if(!dfs(i))
                {
                    ok=false;
                    break;
                }
    
            if(ok) puts("YES");
            else puts("NO");
        }
    
        //system("pause");
        return 0;
    }
    
  • 相关阅读:
    装完某些软件之后IE主页被https://www.hao123.com/?tn=93453552_hao_pg劫持
    Python之向函数传递元组和字典
    Python之变量作用域
    Python之循环遍历
    Python之元组、列表and 字典
    Python数据类型
    Python运算
    Python变量空间
    Python编译源文件& 代码优化
    299. Bulls and Cows
  • 原文地址:https://www.cnblogs.com/fxh0707/p/14470361.html
Copyright © 2011-2022 走看看