hdu 1811 並查集 + 拓撲排序

//2538224 2010-06-13 15:25:40 Accepted 1811 31MS 640K 2121 B C++ T&T
//把=號用並查集處理以後(所有同一集合的數字用根數字來表示)就是顯而易見的拓撲排序了
#include<iostream>
#include<cstdio>
#include<vector>
#include<string>
#define MAX 10010
using namespace std;
vector<int>cost[MAX];
int deep[MAX],count[MAX],save[20005][2];
int find(int x)
{
 int r,j;
 r = x;
 while(r != p[r])
 {
  j = r;
  r = p[r];
  p[j] = p[r];  //壓縮路徑
 }
 return r;
}
void merge(int x,int y)
{
 int fx,fy;
 fx = find(x);
 fy = find(y);
 if(fx != fy)
 {
  if(deep[fx] > deep[fy])
  {
   p[fy] = fx;
  }    //深度小的數加到深度大的樹下可以儘量減少樹的深度減少查詢時間
  else
  {
   p[fx] = fy;
   if(deep[fx] == deep[fy])
   {
    deep[fy]++;   //深度相同的樹相加  數的深度纔會增加
   }
  }
 }
}
int Toposort(int n)
{
 int top = -1,i,k,num = 0,j,x;
 int res = 1;
 for(i = 0; i < n; i++)
 {
  if(count[i] == 0 && find(i) == i)
  {
   count[i] = top;
   top = i;
   num++;
  }
 }
 if(num > 1)
 {
  res = 2;
 }//uncertain
 else if(num == 0)
 {
  return 3;
 }
 for(i = 0; i < n; i++)
 {
  num = 0;
  if(find(i) == i) //這個地方糾結了一個夜 忘了考慮本題不是所有的元素都拿來排序的直接抄模板錯了6 7次
  {//數組下標模擬堆棧
   if(top == -1)//循環次數少於圖的點數 即當所有的點入度都不爲0卻還有點未取出  就是有環存在的情況
   {
   //res = 3;
    return 3; //衝突優於信息不全
   }
   else
   {
    j = top;
    top = count[top];
    for(k = 0; k < cost[j].size(); k++)
    {
     x = cost[j][k];
     if((--count[x]) == 0)
     {
      count[x] = top;
      top = x;
      num++;
     }
    }
    if(num > 1)   //uncertain
    {
     res = 2;
    }
   }
  }
 }

 return res;
}
int main()
{
 int n,m,i,a,b,t,d,ans;
 char sign;
 while(scanf("%d%d",&n,&m) != EOF)
 {
  d = 0;
 // memset(count,0,sizeof(count));
  for(i = 0; i <= n; i++)
  {
   count[i] = 0;
   deep[i] = 1;
   p[i] = i;
   cost[i].clear();
  }
  for(i = 0; i < m; i++)
  {
   scanf("%d%s%d",&a,&sign,&b);
   if(sign != '=')
   {
    if(sign == '>')
    {
     //count[save[i][0]]++;
     t = a;
     a = b;
      b = t;
    }   //這裏先交換保障 save[i][1]要大以便後面的操作
    save[d][0] = a;save[d++][1] = b;
   }
   else
   {
    merge(a,b);    //等於用並查集處理
   }
  }
  for(i = 0; i < d; i++)
  {
   a = find(save[i][0]);
   b = find(save[i][1]);
   cost[a].push_back(b);  //建邊
   count[b]++;
  }
  ans = 1;
  ans = Toposort(n);
  if(ans == 1)
  {
   printf("OK/n");
  }
  else if(ans == 2)
  {
   printf("UNCERTAIN/n");
  }
  else if(ans == 3)
  {
   printf("CONFLICT/n");
  }     
 }
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章