Online JudgeProblem SetAuthorsOnline ContestsUser
Web Board
Home Page
F.A.Qs
Statistical Charts
Problems
Submit Problem
Online Status
Prob.ID:
Register
Update your info
Authors ranklist
Current Contest
Past Contests
Scheduled Contests
Award Contest
User ID:
Password:
  Register

经典并查集,16ms

Posted by Niyada at 2018-08-24 15:31:05 on Problem 1611
#include <iostream>
#include <cstdio>
#include <cmath>
using namespace  std;
const int maxn = 30010;
int a[maxn],f[maxn];
int findx(int x){
    return f[x]<0?x:f[x]=findx(f[x]);
}
void bing(int a,int b){
    int t1 = findx(a);
    int t2 = findx(b);
    if(t1!=t2){
       if(t2==0){
        f[t2]+=f[t1];
        f[t1] = t2;
    }
    else{
        f[t1]+=f[t2];
        f[t2] = t1;
    }
    }
}
int main(){
    int n,m;
    while(scanf("%d%d",&n,&m)!=EOF){
        if(n==0&&m==0)
            break;
        for(int i=0;i<n;++i) f[i] = -1;
        for(int i=1;i<=m;++i){
            int k;
            scanf("%d",&k);
            int t;
            for(int i=1;i<=k;++i){
                if(i==1){
                    scanf("%d",&t);
                    continue;
                }
                int s;
                scanf("%d",&s);
                bing(s,t);
            }
        }
        cout << abs(f[0])<<endl;
    }
    return 0;
}

Followed by:

Post your reply here:
User ID:
Password:
Title:

Content:

Home Page   Go Back  To top


All Rights Reserved 2003-2013 Ying Fuchen,Xu Pengcheng,Xie Di
Any problem, Please Contact Administrator