zoukankan      html  css  js  c++  java
  • (并查集)B

    Description

    There is a town with N citizens. It is known that some pairs of people are friends. According to the famous saying that “The friends of my friends are my friends, too” it follows that if A and B are friends and B and C are friends then A and C are friends, too.

    Your task is to count how many people there are in the largest group of friends.

    Input

    Input consists of several datasets. The first line of the input consists of a line with the number of test cases to follow. The first line of each dataset contains tho numbers N and M, where N is the number of town's citizens (1≤N≤30000) and M is the number of pairs of people (0≤M≤500000), which are known to be friends. Each of the following M lines consists of two integers A and B (1≤A≤N, 1≤B≤N, A≠B) which describe that A and B are friends. There could be repetitions among the given pairs.

    Output

    The output for each test case should contain one number denoting how many people there are in the largest group of friends.

    Sample Input

    Sample Output

    2

    3 2

    1 2

    2 3

    10 12

    1 2

    3 1

    3 4

    5 4

    3 5

    4 6

    5 2

    2 1

    7 10

    1 2

    9 10

    8 9

    简单的压缩查找,没有什么技术含量

    #include<cstdio>
    #include <iostream>
    #include<cstring>
    using namespace std;
    int set[30005];
    int set_find(int x)
    {
    	if(set[x]<0)
    		return x;
    	return set[x]=set_find(set[x]);
    }
    
    
    
    int main ()
    {
    	int n,i,max,x,y,a,b;
    	cin>>n;
    	while(n--)
    	{
    		max=1;
    		memset(set,-1,4*30005);
    		int s[30005] ;
    		for(i=0;i<30005;i++)
    			s[i]=1;
    		cin>>x>>y;
    		for(i=1;i<=y;i++)
    		{
    			cin>>a>>b;
    			int p=set_find(a);
    			int q=set_find(b);
    			if(p!=q)
    			{
    				set[q]=p;
    				s[p]=s[q]+s[p];
    			}
    			max=(max<s[p]?s[p]:max);
    		}
    		cout<<max<<endl;
    	}
    	
    	return 0;
    }
    

  • 相关阅读:
    马尔科夫过程的CKS方程的推导
    科研的一些工具和想法
    读研究生后的一些想法
    读过的一些好书以后可做参考
    latex学习笔记
    机器人工程师学习要求
    《MySQL实战45讲》(8-15)笔记
    《MySQL实战45讲》(1-7)笔记
    java11运行javaFX项目
    ClickHouse入门笔记
  • 原文地址:https://www.cnblogs.com/zswbky/p/5432111.html
Copyright © 2011-2022 走看看