Synthetic Root Plant (Lanqiao Cup)--The Application of Union Check

Synthetic Plants (Blue Bridge Cup) -A plantation using
Planet W, which is divided into m * n small grids (m rows in the east-west direction and n columns in the north-south direction). A synthesizing plant is planted in each grid.
  This kind of plant has a characteristic. Its roots may extend in the north-south or east-west direction, thereby integrating with the plants of another grid.
  
  If we tell you which small grids have roots, can you tell how many syn-root plants are in this garden?

Idea : There are n rows and m columns, that is, there are a total of n*m plants. There may be a connection between them. Here is an agreement that the right side follows the left side as the boss, and of course everyone’s boss at the beginning It's all oneself, so that in the end, you only need to observe how many bosses there are to know how many zygote plants there are.
Note: Remember the principle of "catch the thieves first, catch the king first", that is, if one group follows another group, then their king must follow others. And the "compressed path" is to help find their own boss to be promoted and directly follow the boss.
code show as below:

#include <iostream>
#define maxn 1000000
using namespace std;
int n,m,f[maxn];
void init()
{
    
    
 int i;
 for(i=1;i<=n;i++)
 {
    
    
  f[i]=i;
 }
}
int getf(int x)
{
    
    
 if(f[x]==x)
 {
    
    
  return x;
 }
 else {
    
    
  f[x]=getf(f[x]);
  return f[x];
 }
}
void merge(int v,int u)
{
    
    
 int t1,t2;
 t1=getf(v);//分别寻找两者的boss
 t2=getf(u);
 if(t1!=t2)
 {
    
    
  f[t2]=t1;//两者的boss不是同一个,这里遵循“向左原则”,右边追随左边 
 }
}
int main()
{
    
    
 int i,x,y,sum=0;
 cin>>x>>y;
 n=x*y;
 cin>>m;
 init();//初始化,将n个单独的个体分别设置其追随的boss是自己 
 for(i=1;i<=m;i++)
 {
    
    
  cin>>x>>y;
  merge(x,y);//合并两者 
 }
 for(i=1;i<=n;i++)
 {
    
    
  if(f[i]==i)
  {
    
    
   sum++;
  }
 }
 cout<<endl;
 return 0;
}

Guess you like

Origin blog.csdn.net/HT24k/article/details/106267766