http://acm.hdu.edu.cn/showproblem.php?pid=1811
這題非常經典,花了一個下午才攻克.加強自己的基礎吧.
利用並查集將 '='等號兩邊的數字併入到一個同一個集合,然後構建鄰接表進行拓撲排序.
1: 元素出現相等又不想等的情況 矛盾
2: 有獨立的點 不確定
3:拓撲排序時入度爲 0 的點有多個 矛盾
4: 正確
#include <iostream>
#include <queue>
#include <algorithm>
using namespace std;
typedef struct node
{
int data;
struct node *next;
}node;
typedef struct info
{
int left,right;
char ch;
}info;
int total;
info edge[20001];
node point[20001];
int M,N,in[20001],p[20001];
//初始化鄰接表
void init()
{
for(int i=0;i<N;i++)
{
point[i].data=i;
point[i].next=NULL;
in[i]=0;
p[i]=i;
}
}
//並查集操作
int Find(int x)
{
while(p[x]!=x)x=p[x];
return x;
}
void Union(int x,int y)
{
int px=Find(x),py=Find(y);
if(px!=py)
{
if(px>py)
p[py] = px;
else
p[px] = py;
total--;
}
}
void add(int x,int y)
{
node* temp;
temp = (node*)malloc(sizeof(node));
temp->data=y;
temp->next = point[x].next;
point[x].next = temp;
}
int main()
{
int i,k;
while(~scanf("%d%d",&N,&M))
{
init();
total=N;
/*輸入數據處理相等的情況*/
for(i=0;i<M;i++)
{
scanf("%d %c %d",&edge[i].left,&edge[i].ch,&edge[i].right);
if(edge[i].ch=='=')
{
int x = edge[i].left;
int y = edge[i].right;
Union(x,y);
}
}
/*構建鄰接表*/
bool flag = true;
for(i=0;i<M;i++)
{
if(edge[i].ch=='=')continue;
int x=Find(edge[i].left);
int y=Find(edge[i].right);
if(x==y)flag=false;
if(edge[i].ch=='>')
{
add(x,y);in[y]++;
}
else
{
add(y,x);in[x]++;
}
}
/*拓撲排序*/
queue<int>q;
for(k=0;k<N;k++)
{
if(in[k]==0&&k==Find(k))
q.push(k);
}
int mark=0;
while(!q.empty())
{
if(q.size()>1)mark=1;
int fr=q.front();
q.pop();total--;
for(node* u=point[fr].next;u;u=u->next)
if(--in[u->data]==0)
q.push(u->data);
}
if(!flag||total>1)
cout<<"CONFLICT"<<endl;
else if(mark)
cout<<"UNCERTAIN"<<endl;
else
cout<<"OK"<<endl;
}
return 0;
}