PAT 甲级 1034 Head of a Gang (并查集)(c++版)(python版)(附代码注释)

1034 Head of a Gang (30 分)

原文链接:http://kakazai.cn/index.php/Kaka/Pat/query/id/124

题目

题目链接:https://pintia.cn/problem-sets/994805342720868352/problems/994805456881434624

One way that the police finds the head of a gang is to check people’s phone calls. If there is a phone call between A and B, we say that A and B is related. The weight of a relation is defined to be the total time length of all the phone calls made between the two persons. A “Gang” is a cluster of more than 2 persons who are related to each other with total relation weight being greater than a given threthold K. In each gang, the one with maximum total weight is the head. Now given a list of phone calls, you are supposed to find the gangs and the heads.

Input Specification:

Each input file contains one test case. For each case, the first line contains two positive numbers N and K (both less than or equal to 1000), the number of phone calls and the weight threthold, respectively. Then N lines follow, each in the following format:

Name1 Name2 Time

where Name1 and Name2 are the names of people at the two ends of the call, and Time is the length of the call. A name is a string of three capital letters chosen from A-Z. A time length is a positive integer which is no more than 1000 minutes.

Output Specification:

For each test case, first print in a line the total number of gangs. Then for each gang, print in a line the name of the head and the total number of the members. It is guaranteed that the head is unique for each gang. The output must be sorted according to the alphabetical order of the names of the heads.

Sample Input 1:

8 59
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10

Sample Output 1:

2
AAA 3
GGG 3

Sample Input 2:

8 70
AAA BBB 10
BBB AAA 20
AAA CCC 40
DDD EEE 5
EEE DDD 70
FFF GGG 30
GGG HHH 20
HHH FFF 10

Sample Output 2:

0

题意分析

将人看成点,人与人之间的通话看成边,构成一个图。边的权重是通话的总时长,点的权重是与其相连的边的总权重,图中的连通块的权重是其所有边的权重之和。连通块中权重最大的点是队首。而gang是图中的连通块,且它的点数大于2,权重大于给定的阈值。

现在要找出有多少个这样的连通块,而且要找出连通块中的点数和其队首,而且连通块要按队首的编号升序排列。

并查集:本题的关键任务是,若人a位于连通块A,人b位于连通块B,而a和b之间有通话,则要合并连通块A和B。将连通块看成集合,问题转化为,若元素a位于集合A,元素b位于集合B,而a和b之间有联系,则合并集合A和B。因此,可以用并查集。

知识点与坑点

  • 知识点

1)并查集

  • 坑点

1)最后结果,若不进行排序,则测试点2,和测试点5会出错

一、并查集

算法思路

1 将每个人看成一个独立的连通块。若人A与人B之间有通话,则合并它们各自所在的连通块,得到一个更大的连通块。

2 在输入每条通话记录时,要累加每个人的总通话时长,即其权重。

3 合并完所有连通块后,每个连通块的权重是每个人的权重总和的一半。

代码-c++版
#include <iostream>
#include<algorithm>
#include<set>
#include<map>
using namespace std;

/*数值范围*/ 
const int maxn = 2001;	//最多有1000条通话记录,最多有2000个人 

/*所有变量*/ 
int father[maxn];	//并查集数组
int call[maxn];  //存储每个的总通话时长  
struct node {	//定义每个连通块的属性 
int c,call,head;	//总人数,总权重,队首整数编号
}gang[maxn];

/* 并查集-初始化*/
void initiate(){
  for(int i=0;i<maxn;i++){
   father[i]=i;
  }
}
/* 并查集-找根结点+压缩路径*/
int findroot(int a){
 int x = a;
 while(a != father[a]) {
  a = father[a];
 }
 int temp; 
 while(x != father[x]){
  temp = father[x];
  father[x] = a;
  x = temp;
 }
 return a;
}
/* 并查集-合并集合+保证根结点编号最小*/ 
 void union_ab(int a,int b){
  int fa = findroot(a);
  int fb = findroot(b);
  if(fa <= fb){ 
   father[fb] = fa;
  }else{
   father[fa] = fb;
  }
 }

/* 编号由字符串转整数;再由整数取字符串 */
int num = 1; //编号从1开始,不能从0开始,因为0要作为默认队首 
map<string, int> m;	//由字符串转整数
map<int, string> rm;	//由整数取字符串
int getid(string s) {
	//在m中找不到字符串,即字符串还没整数编号 
    if (m.find(s) == m.end()) { 
        m[s] = num; //给予整数编号 
        rm[num] = s; //整数为键,字符串为值,存好 
        num++;  
    }
    return m[s];	//返回整数编号 
}

/* 比较规则 */ 
int cmp(node a, node b) {
    return rm[a.head] < rm[b.head]; //按队首的字符串编号升序排列
}

int main(){
	
initiate();
int n,cmax;	//cmax是连通块的权重阈值 
scanf("%d %d",&n,&cmax);

/* 累计每人的通话记录时长,合并有关人员所在集合 */ 
int in1;    
string a, b;
for (int i = 0; i < n; i++) {
cin >> a >> b;
int id1 = getid(a);	//获得整数编号 
int id2 = getid(b);
union_ab(id1, id2);
scanf("%d", &in1);
call[id1] += in1;	//累计每个人的通话时长
call[id2] += in1;
}
/* 遍历所有人,累计其所在连通块的各属性 */ 
for (int i = 1; i < num; i++) {
	int fa = findroot(i);	//根结点就是连通块编号 
	gang[fa].c++;  	//人数增加1 
	gang[fa].call += call[i]; //总权重增加 
	if (call[gang[fa].head] < call[i]) {	//更换队首 
	gang[fa].head = i;
	}
 }
 
sort(gang+1, gang + num, cmp); //对gang进行排序

/* 找出符合条件的连通块 */
set<int> s; 	//存储符合条件的连通块的整数编号
for (int i = 1; i < num; i++) {
	if(gang[i].c > 2 && gang[i].call > 2* cmax){
		s.insert(i);
	}
 }
    
/* 按要求输出 */
printf("%d\n",s.size());
set<int>::iterator it;
for (it = s.begin(); it != s.end(); it++) {
	cout << rm[gang[*it].head] << " " << gang[*it].c << endl;
}

 return 0;
}
代码-python版
#!/usr/bin/python3
#code-python(3.6)

#并查集-找根结点
def findroot(a):
    while(father[a]!=a):
        a = father[a]
    return a

#并查集-合并集合+保证根结点最小
def union_ab(a,b):
    fa = findroot(a)
    fb = findroot(b)
    if(fa <= fb):
        father[fb] = fa
    else:
        father[fa] = fb

#接收输入
line = input().split(" ")
n = int(line[0])
cmax = int(line[1]) #cmax是连通块的权重阈值

call = {}   #记录每人的累计通话记录时长
father = {} #记录每人的父结点

for i in range(n):
    line = input().split(" ")   #接受每行,并用空格分开
    a,b,t= line[0],line[1],int(line[2])
    #累计每人的通话时长
    if a not in call:
        call[a] = 0
    if b not in call:
        call[b] = 0
    call[a] += t
    call[b] += t
    #合并每人所在的集合
    if a not in father: #若首次出现,则初始化其根结点
        father[a] = a
    if b not in father:
        father[b] = b
    union_ab(a,b)

#遍历所有人,统计它们所在的连通块
gang = {}
call['AAAA'] = 0
for key,value in father.items():
    root = findroot(key)
    if root not in gang:
        gang[root] = [0,0,'AAAA']
    gang[root][0] += call[key] #连通块权重增加
    gang[root][1] += 1  #该连通块人数增加
    if call[key] >= call[gang[root][2]] :    #若该人权重更大,更换队首
        gang[root][2] = key

#删除不合格的连通块
for key in list(gang.keys()):
     if gang[key][0] <= 2*cmax :
         del gang[key]
     elif gang[key][1] <= 2:
         del gang[key]

#对连通块排序
x = sorted(gang.items(),key = lambda x:(x[1][2])) #按队首名称升序,sort不会改变原序列,返回新序列

#按要求输出
print(len(x))
for i in x:
    print(i[1][2],i[1][1])

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值