zoukankan      html  css  js  c++  java
  • 蓝桥 历届试题 合根植物

    虽然思路很简单是裸的并查集,但是代码要注意细节,我在写的时候就忘了写判断语句 if(af != bf) f[bf] = a;

    #include <iostream>
    #include <cstdio>
    using namespace std;
    const int maxn = 1e6+50;
    int n,m,t,f[maxn];
    int getf(int x)
    {
    	if(f[x] == x) return x;
    	f[x] = getf(f[x]);
    	return f[x];
    }
    void merge(int a,int b){
    	int af = getf(a);
    	int bf = getf(b);
    	if(af != bf) f[bf] = a; //就是这!!只有两个人属于不同首领才进行融合!!
    }
    int main()
    {
    	scanf("%d%d",&n,&m); 
    	for(int i = 1; i <= n*m; i++) f[i] = i;
    	scanf("%d",&t);
    	for(int i = 1; i <= t; i++){
    		int x,y;
    		scanf("%d%d",&x,&y);
    		merge(x,y);
    	}
    	int ans = 0;
    	for(int i = 1; i <= n*m; i++) cout<<i<<" ";
    	cout<<endl; 
    	for(int i = 1; i <= n*m; i++){
    		if(f[i] == i) ans++;
    		cout<<f[i]<<" ";
    	}
    	cout<<ans<<endl;
    	return 0;
    }
    
    

    总结:并查集在融合时的判断语句!在融合时的判断语句!在融合时的判断语句!重要的说三遍!!

    "没有天赋异禀,那就加倍努力"
  • 相关阅读:
    函数对象中的prototype属性
    undefined和null的区别
    访问修饰符
    继承
    静态成员和实例成员的区别
    js模拟Trim()方法
    连接池的执行原理
    Javascript中的= =(等于)与= = =(全等于)区别
    数据库中创建约束
    KM算法入门
  • 原文地址:https://www.cnblogs.com/Beic233/p/13168227.html
Copyright © 2011-2022 走看看