【拓扑排序】 HDOJ 1811 Rank of Tetris

先用并查集缩点,然后拓扑排序就行了。。。判断信息不完整可以看队列里的元素个数,如果大于1则肯定是信息部完整。。。

#include <iostream>  
#include <queue>  
#include <stack>  
#include <map>  
#include <set>  
#include <bitset>  
#include <cstdio>  
#include <algorithm>  
#include <cstring>  
#include <climits>  
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 10005
#define maxm 20005
#define eps 1e-10
#define mod 998244353
#define INF 999999999
#define lowbit(x) (x&(-x))
#define mp mark_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid  
#define rson o<<1 | 1, mid+1, R  
typedef long long LL;
//typedef int LL;
using namespace std;
LL powmod(LL a, LL b){LL res=1,base=a;while(b){if(b%2)res=res*base%mod;base=base*base%mod;b/=2;}return res;}
void scanf(int &__x){__x=0;char __ch=getchar();while(__ch==' '||__ch=='\n')__ch=getchar();while(__ch>='0'&&__ch<='9')__x=__x*10+__ch-'0',__ch = getchar();}
// head

int h[maxn], next[maxm], v[maxm];
int H[maxn], NEXT[maxm], V[maxm];
int f[maxn], in[maxn], id[maxn];
char s[100];
queue<int> q;
int cnt, n, m, CNT;

int find(int x)
{
	return x == f[x] ? f[x] : f[x] = find(f[x]);
}
void init(void)
{
	cnt = CNT = 0;
	memset(in, 0, sizeof in);
	memset(h, -1, sizeof h);
	memset(H, -1, sizeof H);
	for(int i = 0; i <= n; i++) f[i] = i;
}
void addedges(int u, int vv)
{
	next[cnt] = h[u], h[u] = cnt, v[cnt] = vv, cnt++;
}
void Addedges(int u, int vv)
{
	NEXT[CNT] = H[u], H[u] = CNT, V[CNT] = vv, CNT++;
}
void narrow(void)
{
	m = 0;
	for(int i = 0; i < n; i++) if(find(i) == i) id[f[i]] = ++m;
	for(int i = 0; i < n; i++)
		for(int e = H[i]; ~e; e = NEXT[e])
			addedges(id[f[i]], id[f[V[e]]]), in[id[f[V[e]]]]++;
}
void debug(void)
{
	for(int i = 1; i <= m; i++) {
		printf("%d :: ", i);
		for(int e = h[i]; ~e; e = next[e])
			printf("%d ", v[e]);
		printf("\n");
	}
}
void work(void)
{
	int ok = 1, a, b, aa, bb, inq, num;
	while(m--) {
		scanf("%d%s%d", &a, s, &b);
		aa = find(a), bb = find(b);
		if(s[0] == '=') {
			if(aa > bb) f[aa] = bb;
			else f[bb] = aa;
		}
		if(aa == bb && s[0] != '=') ok = 0;
		if(s[0] == '>') Addedges(b, a);
		if(s[0] == '<') Addedges(a, b);
	}
	if(!ok) {
		printf("CONFLICT\n");
		return;
	}
	narrow();
	inq = num = 0;
	for(int i = 1; i <= m; i++)
		if(!in[i]) {
			q.push(i);
			inq++, num++;
			if(inq > 1) ok = 0;
		}
	while(!q.empty()) {
		int u= q.front(); q.pop(), inq--;
		for(int e = h[u]; ~e; e = next[e]) {
			in[v[e]]--;
			if(!in[v[e]]) {
				q.push(v[e]);
				inq++, num++;
				if(inq > 1) ok = 0;
			}
		}
	}
	if(num < m) printf("CONFLICT\n");
	else if(!ok) printf("UNCERTAIN\n");
	else printf("OK\n");
}
int main(void)
{
	while(scanf("%d%d", &n, &m)!=EOF) {
		init();
		work();
	}
	return 0;
}


你可能感兴趣的:(HDU)