1 条题解

  • 0
    @ 2024-12-24 10:06:02

    C :

    #include <stdio.h>
    #include <stdlib.h>
    #include <string.h>
    
    int f[30010], weight[30010];
    
    int find(int v){
    if(v == f[v])return v;
    int F = find(f[v]);
    f[v] = F;
    return F;
    }
    
    int main()
    {
        int n, m;
        while(scanf("%d%d",&n,&m) != EOF){
            for(int i = 0;i <= n; i++)f[i] = i;
            memset(weight,0,sizeof(weight));
            while(m--){
                int k,first;
                scanf("%d%d",&k,&first);
                int fa = find(first);
                while(--k){
                    int b;
                    scanf("%d",&b);
                    int fb = find(b);
                    f[fb] = fa;
                }
            }
            int max = 0;
            for(int i = 1;i <= n; i++){
                int fa = find(i);
                weight[fa]++;
            }
            for(int i = 1;i <= n; i++){
                if(max < weight[i])max = weight[i];
            }
            printf("%d\n",max);
        }
    
        return 0;
    }
    

    C++ :

    #include <iostream>
    #include <cstdio>
    #include <cstring>
    #include <algorithm>
    
    using namespace std;
    
    const int maxn=30010;
    
    int pre[maxn],a[maxn],h[maxn];
    
    int find(int x)
    {
        int r=x;
        while(r!=pre[r]) r=pre[r];
        int temp;
        while(x!=r)
        {
            temp=pre[x];
            pre[x]=r;
            x=temp;
        }
        return r;
    }
    
    void join(int x,int y)
    {
        int fx=find(x);
        int fy=find(y);
        if(fx!=fy) pre[fx]=fy;
    }
    
    int main()
    {
        int n,m;
        while(scanf("%d%d",&n,&m)!=EOF)
        {
            for(int i=1;i<=n;i++) pre[i]=i;
            memset(h,0,sizeof(h));
            int num;
            for(int i=0;i<m;i++)
            {
                scanf("%d",&num);
                for(int j=0;j<num;j++) scanf("%d",&a[j]);
                for(int j=1;j<num;j++) join(a[0],a[j]);
            }
            for(int i=1;i<=n;i++) h[find(i)]++;
            int k=1;
            for(int i=2;i<=n;i++)
            {
                if(h[i]>h[k]) k=i;
            }
            printf("%d\n",h[k]);
        }
    }
    
    
    • 1

    信息

    ID
    1825
    时间
    1000ms
    内存
    32MiB
    难度
    (无)
    标签
    递交数
    0
    已通过
    0
    上传者