并查集运用

一看到这种求连通关系的就要想到使用并查集

腾讯例题:

现在有10000000个用户,编号为1- 10000000,现在已知有m对关系,每一对关系给你两个数x和y,代表编号为x的用户和编号为y的用户是在一个圈子中,例如:A和B在一个圈子中,B和C在一个圈子中,那么A,B,C就在一个圈子中。现在想知道最多的一个圈子内有多少个用户。 

解答:

import java.util.*;
import java.util.Scanner;

class UnionFind{
    public static int[] people = new int[10000001]; //编号从1开始
    public static int[] numFriends = new int[10000001];
    
    public UnionFind(){
        for(int i = 0; i < 10000001; i++){
            people[i] = i;
            numFriends[i] = 1;
        }
    }
    
    public int find(int x){
        while(x != people[x]){
            people[x] = people[people[x]];
            x = people[x];
        }
        return x;
    }
    
    public void union(int x, int y){
        int x_people = find(x);
        int y_people = find(y);
        people[x_people] = y_people;
        if(x_people == y_people) return;
        numFriends[x_people] += numFriends[y_people];
        numFriends[y_people] = numFriends[x_people];
    }
}

public class Main{
    public static void main(String[] args){
        Scanner sc = new Scanner(System.in);
        int numTest = sc.nextInt();
        for(int i = 0; i < numTest; i++){
            int numRelation = sc.nextInt();
            UnionFind uf = new UnionFind();
            for(int j = 0; j < numRelation; j++){
                int x = sc.nextInt();
                int y = sc.nextInt();
                uf.union(x, y);
            }
            int res = 0;
            for(int k = 0; k < 10000001; k++){
                res = Math.max(res, uf.numFriends[k]);
            }
            System.out.println(res);
        }
    }
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值