zoukankan      html  css  js  c++  java
  • poj 2524

    并查集水题

    #include <iostream>
    using namespace std;
    const int maxn=50010;
    int tot,m,n;
    struct node
    {
    	int rank;
    	int data;
    	int parent;
    }t[maxn];
    void init()
    {
    	for(int i=1;i<=n;i++)
    	{
    		t[i].data=i;
    		t[i].rank=1;
    		t[i].parent=i;
    	}
    }
    int find(int p)
    {
    	if(p!=t[p].parent)
    		t[p].parent=find(t[p].parent);//路径压缩
    	return t[p].parent;//易错点
    }
    void Union(int x,int y)
    {
    	int xp=find(x);
    	int yp=find(y);
    	if(xp!=yp)
    	{
    		if(t[xp].rank<t[yp].rank)//按秩的大小合并,和上面的路径压缩的作用一样都是提高了查找速度
    			t[xp].parent=yp;
    		else
    		{
    			t[yp].parent=xp;
    			if(t[xp].rank==t[yp].rank)
    				t[xp].rank++;
    		}
    		tot--;
    	}
    }
    int main()
    {
    	int x,y,amount=0;
    	while(cin>>n>>m&&!(n==0&&m==0))
    	{
    		init();
    		amount++;
    		tot=n;
    		for(int i=0;i<m;i++)
    		{
    			cin>>x>>y;
    			Union(x,y);
    		}
    		cout<<"Case "<<amount<<": "<<tot<<endl;
    	}
    	return 0;
    }


     

  • 相关阅读:
    从up6-down2升级到down3
    XproerIM产品使用手册
    Web大文件上传控件-asp.net-bug修复-Xproer.HttpUploader6.2
    WordPaster-Chrome浏览器控件安装方法
    poj1009
    poj1012
    poj1016
    poj1019
    poj1023
    poj1026
  • 原文地址:https://www.cnblogs.com/lj030/p/3002308.html
Copyright © 2011-2022 走看看