当前位置:编程学习 > C/C++ >>

hdu 1811-Rank of Tetris(并查集+拓扑排序)

/*

  并查集处理=,然后拓扑排序  当队中超过1个元素时是条件不足,若没有用完所给的条件则是出现冲突

*/

#include<cstdio>

#include<cstring>
#include<vector>
#include<queue>
using namespace std;
int u[10010],v[10010],p[10010],deg[10010];
char opr[10010];
vector<int> G[10010];
int sum;
int find(int x)
{
    return x==p[x]?x:p[x]=find(p[x]);
}
int init(int n)
{
    for(int i = 0; i <= n; i++)
    {
        p[i] = i;
        G[i].clear();
        deg[i] = 0;
    }
}
int topo(int n)
{
    queue<int>q;
    for(int i = 0; i < n; i++)
        if(!deg[i]&&find(i)==i)
            q.push(i);
    int flag=0;
    while(!q.empty())
    {
        if(q.size()>1) flag=1;
        int x = q.front();
        q.pop();
        sum--;
        for(int i = 0; i < G[x].size(); i++)
        {
            int y = G[x][i];
            if(--deg[y]==0)
            {
                q.push(y);
            }
        }
    }
    if(sum>0) puts("CONFLICT");
    else if(flag) puts("UNCERTAIN");
    else puts("OK");
}
int main()
{
    int n,m;
    while(scanf("%d %d",&n,&m)==2)
    {
        init(n);
        sum = n;
        for(int i = 0; i < m; i++)
        {
            scanf("%d %c %d",&u[i],&opr[i],&v[i]);
            if(opr[i]=='=')
            {
                int x = find(u[i]);
                int y = find(v[i]);
                if(x!=y)
                    {p[y] = x;
                sum--;}
            }
        }
        for(int i = 0; i < m; i++)
        {
            if(opr[i]=='=') continue;
            int x = find(u[i]);
            int y = find(v[i]);
            if(opr[i]=='>')
            {
                G[x].push_back(y);
                deg[y]++;
            }
            else
            {
                G[y].push_back(x);
                deg[x]++;
            }
        }
        topo(n);
    }
    return 0;
}

补充:软件开发 , C++ ,
CopyRight © 2022 站长资源库 编程知识问答 zzzyk.com All Rights Reserved
部分文章来自网络,