zoukankan      html  css  js  c++  java
  • 数据结构与算法题目集(中文)7-25 朋友圈 (25分) 并查集

    1.题目

    某学校有N个学生,形成M个俱乐部。每个俱乐部里的学生有着一定相似的兴趣爱好,形成一个朋友圈。一个学生可以同时属于若干个不同的俱乐部。根据“我的朋友的朋友也是我的朋友”这个推论可以得出,如果A和B是朋友,且B和C是朋友,则A和C也是朋友。请编写程序计算最大朋友圈中有多少人。

    输入格式:

    输入的第一行包含两个正整数N(≤30000)和M(≤1000),分别代表学校的学生总数和俱乐部的个数。后面的M行每行按以下格式给出1个俱乐部的信息,其中学生从1~N编号:

    第i个俱乐部的人数Mi(空格)学生1(空格)学生2 … 学生Mi

    输出格式:

    输出给出一个整数,表示在最大朋友圈中有多少人。

    输入样例:

    7 4
    3 1 2 3
    2 1 4
    3 5 6 7
    1 6
    

    输出样例:

    4

    2.题目分析

    典型的使用并查集实现。查找节点的“掌门”,之后将批次的掌门连接

    具体并查集讲解(强烈推荐):https://www.cnblogs.com/xzxl/p/7226557.html 

    3.代码

    #include<iostream>
    using namespace std;
    int list[30001] = {0};
    int pre[30001];
    int find(int root)
    {
    	int son, temp;
    	son = root;
    	while (root != pre[root])
    		root = pre[root];
    	while (son != root)
    	{
    		temp = pre[son];
    		pre[son] = root;
    		son = temp;
    	}
    	return root;
    	
    }
    	
    void join(int root1, int root2)
    {
    	int x; int y;
    	x = find(root1);
    	y = find(root2);
    	if (x != y)
    		pre[x] = y;
    }
    
    
    int main()
    {
    
    	int n, m;
    	cin >> n >> m;
    	for (int i = 0; i < n; i++)
    		pre[i] = i;
    	for (int i = 0; i < m; i++)
    	{
    		int a, b;
    		cin >> a >> b;
    		for (int j = 1; j < a; j++)
    		{
    			int temp;
    			cin >> temp;
    			join(b, temp);
    		}
    	
    	}
    	int max = 0;
    	for (int i = 1; i <=n; i++)
    	{
    		int root = find(i);
    		list[root]++;
    		if (list[root] > max)
    			max = list[root];
    	}
    
    		cout << max << endl;
    
    }
  • 相关阅读:
    前端博客收集
    Oracle 数据库性能调优
    vue解决跨域问题
    IIS相关问题及解决方案
    《软件测试工程师》学习笔记
    Matlab学习笔记(一)
    排序算法及分析
    Silverlight学习笔记——跨域调用
    Matlab学习笔记(三)
    C#的一些必备技术
  • 原文地址:https://www.cnblogs.com/Jason66661010/p/12789011.html
Copyright © 2011-2022 走看看