并查集--城市团伙

一.题目描述:

在某个城市里住着n个人,任何两个认识的人不是朋友就是敌人,而且满足:

    l我朋友的朋友是我的朋友;

    l我敌人的敌人是我的朋友;

    l已知关于n个人的m条信息(即某2个人是朋友或者敌人),假设所有是朋友的人一定属于同一个团伙,请计算该城市最多有多少团伙?

二.题目解析:

利用并查集来维护团伙关系,初始是每个人都是一个团伙,然后遍历输入的每一条关系并处理,如果是朋友则两个团伙合并并做路径压缩,同时团伙数减一。

三.相关代码:

第1行为n和m,1<n<1000,1≤m≤100 000;以下m行,每行为p x y,p的值为0或1,p为0时,表示x和y是朋友,p为1时,表示x和y是敌人。

输出结果为最多团伙数。

import java.util.Scanner;

/**

* 团伙问题(并查集)

*/

public class test6 {

/**

* 记录团伙关系

*/

static int[] persons;

static int number;

/**

* 人数

*/

static int n;

/**

* 关系数

*/

static int m;

public static void main(String[] args) {

Scanner scanner = new Scanner(System.in);

n = scanner.nextInt();

m = scanner.nextInt();

persons=new int[n+1];

number=n;

int p,x,y;

for (int i = 0; i < m; i++) {

p=scanner.nextInt();

x=scanner.nextInt();

y=scanner.nextInt();

if (p==0){

if (merge(x,y)!=0){

number–;

}

}

}

System.out.println(number);

}

/**

* 寻找根节点

*

* @param i

* @return

*/

private static int findUnion(int i) {

/**

* 合并集的根

*/

if (persons[i] != 0) {

int root = findUnion(persons[i]);

//路径压缩

persons[i] = root;

return root;

} else {

return i;

}

}

private static int merge(int x, int y) {

int root1 = findUnion(x);

int root2 = findUnion(y);

if (root1 != root2) {

persons[root2] = root1;

return root1;

} else {

return 0;

}

}

}

四.结果展示:

[外链图片转存失败,源站可能有防盗链机制,建议将图片保存下来直接上传(img-gGHuLrwl-1658403978957)(C:\Users\USER\AppData\Roaming\Typora\typora-user-images\image-20220721194421037.png)]
!= root2) {

persons[root2] = root1;

return root1;

} else {

return 0;

}

}

}

四.结果展示:

在这里插入图片描述

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Riley_Yu

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值