hdu-1811 Rank of Tetris 并查集+拓扑

题目链接



#include 
#include 
#include 
#include 
#include 
#include 
using namespace std;
typedef long long LL;
const int maxn = 10005;
const int Mod = 1000000007;
int n,m,num,flag,ok;
int p[maxn];
int a[maxn<<1],b[maxn<<1],in[maxn];
char ch[maxn<<1];
vectormap[maxn];
int find( int x )
{
    return p[x] == x?x:p[x] = find( p[x] );
}
void merge( int a,int b )
{
    int x = find( a );
    int y = find( b );
    if( x != y )
    {
        p[x] = y;
        num --;
    }
}
void Topo()
{
    queueque;
    for( int i = 0; i < n; i ++ )
    {
        if( in[i] == 0 && i == find( i ) )
            que.push( i );
    }
    while( !que.empty() )
    {
        if( que.size() > 1 )    ok = 0;
        int u = que.front(); que.pop();
        num --;
        for( int i = 0; i < map[u].size(); i ++ )
        {
            int v = map[u][i];
            if( -- in[v] == 0 )
                que.push( v );
        }
    }
}
void init()
{
    flag = 0; num = n; ok = 1;
    for( int i = 0; i < n; i ++ ){    
        p[i] = i;  in[i] = 0;
        map[i].clear();
    }
}
int main()
{
    #ifndef ONLINE_JUDGE     
    freopen("data.txt","r",stdin);     
    #endif 
    while( scanf("%d%d",&n,&m) != EOF )
    {
        init();
        for( int i = 1; i <= m; i ++ )
        {
            scanf("%d %c %d",&a[i],&ch[i],&b[i]);
            if( ch[i] == '=' )
                merge( a[i],b[i] );
        }
        for( int i = 1; i <= m; i ++ )
        {
            if( ch[i] == '=' )    continue;
            int fx = find( a[i] );
            int fy = find( b[i] );
            if( fx == fy ){    
                flag = 1;
                break;
            }
            if( ch[i] == '>' )
            {
                map[fx].push_back( fy );
                in[fy] ++;
            }
            else if( ch[i] == '<' )
            {
                map[fy].push_back( fx );
                in[fx] ++;
            }
        }
        if( flag )
            printf("CONFLICT\n"); 
        else
        {
            Topo();
            if( num > 1 )    printf("CONFLICT\n"); 
            else if( ok )  printf("OK\n");
            else printf("UNCERTAIN\n");  
        }
    }
    return 0;
}


你可能感兴趣的:(数据结构-并查集)