• 5-25 朋友圈


                                   5-25 朋友圈(25分)(经典的并查集算法题)

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

    输入格式:

    输入的第一行包含两个正整数N(le≤30000)和M(le≤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

    代码:
     1 #include<iostream>
     2 #include<stdio.h>
     3 #include<math.h>
     4 #include<string.h>
     5 #include<vector>
     6 #include<list>
     7 #include<algorithm>
     8 using namespace std;
     9 int a[30030];
    10 int ans;
    11 int find(int x){
    12     if(a[x]>=0){
    13         a[x] = find(a[x]);
    14         return a[x];
    15     }
    16     return x;
    17 }
    18 void union_(int x,int y){
    19     int tx = find(x);
    20     int ty = find(y);
    21     if(tx==ty) return ;
    22     a[tx] += a[ty];
    23     a[ty] = tx;
    24     if(a[tx]<ans)    ans = a[tx];
    25 }
    26 
    27 int main(){
    28     int n,m;
    29     scanf("%d%d",&n,&m);
    30     for(int i=0;i<=n;i++){
    31         a[i] = -1;
    32     }
    33     ans = -1;
    34     for(int i=0;i<m;i++){
    35         int t,temp=0,x;
    36         scanf("%d",&t);
    37         if(t>=1)
    38             scanf("%d",&temp);
    39         for(int j=1;j<t;j++){
    40             scanf("%d",&x);
    41             union_(temp,x);
    42         }
    43     }
    44     printf("%d
    ",-ans);
    45     return 0;
    46 }
     
  • 相关阅读:
    利用ResultFilter实现asp.net mvc3 页面静态化
    c#的DateTime.Now函数详解
    C#中使用DES和AES加密解密
    C#实现DES加密解密,AES加密解密
    MyEclipse的破解代码,适用各个版本
    C# DataGridView分页显示
    C# 对话框使用大全
    C# 通过串口发送短信
    C# axWindowsMediaPlayer制作播放器
    C#关于log4net(Log For Net)
  • 原文地址:https://www.cnblogs.com/guohaoyu110/p/6384515.html
Copyright © 2020-2023  润新知