5-30 並查集 tree

#include <iostream>

#include <fstream>

using namespace std;

ifstream fin("tree.in");

ofstream fout("tree.out");

#define cin fin

#define cout fout

int fa[100001];

bool check[1000001];

int u_f(int x)

{

   int root=x;

   while(fa[root]!=root) root=fa[root];  //找出他的根

   while(fa[x]!=x)     //壓縮路徑

{

      int y=fa[x];

      fa[x]=root;

      x=y;

   }

   return root;

}

 

int main()

{

   int n,m;

   cin>>n>>m;

   for(int i=1;i<=n;i++)

   {

      fa[i]=i;

      check[i]=true;

   }

     

   for(int i=0;i<m;i++)

   {

      int x,y;

      cin>>x>>y;

      int fx=u_f(x);

      int fy=u_f(y);

      if(fx!=fy)

        fa[fy]=fx;

      else check[fx]=false;  //便於排除 環形樹  的情況

   }

   int ans=0;

   for(int i=1;i<=n;i++)

      if(fa[i]==i && check[i]) ans++;      //求數量

   cout<<ans;

   return 0;

}

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