团伙(并查集经典)

题目大体的说:

1.我朋友的朋友是我的朋友;

 2.我敌人的敌人是我的朋友;

所有是朋友的人组成一个团伙。告诉你关于这N个人的M条信息,即某两个人是朋友,或者某两个人是敌人,请你编写一个程序,计算出这个城市最多可能有多少个团伙?

方法:

 1 #include<cstdio>
 2 #include<cstring>
 3 long n,m,x,y,re=0,b,r1,r2;
 4 long father[1001],a[1001][1001];
 5 long find (long);
 6 int main()
 7 {
 8     memset(a,0,sizeof(a));
 9     scanf("%d %d",&n,&m);
10     for(int i=1;i<=n;i++)
11     father[i]=i;
12      for(int i=1;i<=m;i++)
13      {
14          scanf("%d %d %d",&b,&x,&y);
15          if(b==0)
16          {
17              r1=find(x);
18              r2=find(y);
19              father[r2]=r1;
20          }
21          if(b==1)
22          for(int j=1;j<=a[x][0];j++)
23          {
24              r1=find(y);
25              r2=find(a[x][j]);
26              father[r2]=r1;
27          }
28          for(int j=1;j<=a[y][0];j++)
29          {
30              r1=find(x);
31              r2=find(a[y][j]);
32              father[r2]=r1;
33          }
34          a[x][0]++;
35          a[y][0]++;
36          a[x][a[x][0]]=y;
37          a[y][a[y][0]]=x;
38      }
39      for(int i=1;i<=n;i++)
40      if(father[i]=i)
41      re++;
42      printf("%d",re);
43 }
44 long find(long x)
45 {
46     if(father[x]!=x)
47     father[x]=find(father[x]);
48     return father[x];
49 }

 

转载于:https://www.cnblogs.com/gzy20020702/p/7412915.html

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值