PAT.A1034 Head of a Gang

Back to ContentsInsert picture description here

Title

Given the length of a conversation between several people (regarded as an undirected edge), divide them into groups according to these conversations. The total edge weight of each group is set to the sum of the length of all calls in the group, and the point weight of each person is set to the sum of the length of the calls that the person participates in. Now a threshold K is given, and as long as the total margin of a group exceeds K, and the number of members exceeds 2, the group is regarded as a "gang", and the person with the largest point weight in the group is regarded as Boss. It is required to output the number of "criminal gangs", and to output the names of the leaders and the number of members of each "criminal gang" in ascending order of the names of the leaders.

Sample (can be copied)

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
//output
2
AAA 3
GGG 3
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
//output
0

important point

  1. This question uses the adjacency matrix to store the call record graph, if you use the adjacency table will be quite troublesome.
  2. In addition to using DFS traversal, this problem can also be solved by means of a check, but it is relatively cumbersome. When merging and checking sets, remember to keep the node with the largest full value as the root node.
#include <bits/stdc++.h>
using namespace std;

const int maxn=2010;
int n,k,num=0;//总通话记录数,阈值,总人数 
map<string,int> stringint;//姓名->编号
map<int,string> intstring;//编号->姓名
map<string,int> gang;//黑帮头目--黑帮人数 
int G[maxn][maxn]={0};//通话记录图,邻接矩阵存储 
int W[maxn] ={0};//每个人的权重 
bool flag[maxn]={false};
int change(string s){
	if(stringint.find(s)!=stringint.end()){
		return stringint[s];
	}else{
		stringint[s]=num;
		intstring[num]=s;
		return num++;
	}
}
void DFS(int now,int& head,int& numperson,int& totalw){
	flag[now]=true;
	numperson++;
	if(W[now]>W[head])head=now;
	for(int i=0;i<num;i++){
		if(G[now][i]>0){
			totalw+=G[now][i];
			G[now][i]=G[i][now]=0;//删除该边,防止回头
			if(!flag[i])DFS(i,head,numperson,totalw);
		}
	}
}
int main(){
    int w;
    string s1,s2;
	cin>>n>>k;
	for(int i=0;i<n;i++){
		cin>>s1>>s2>>w;
		int id1=change(s1);
		int id2=change(s2);
		W[id1]+=w;
		W[id2]+=w;
		G[id1][id2]+=w;
		G[id2][id1]+=w;
	}
	for(int i=0;i<num;i++){
		if(!flag[i]){
			int head=i,numperson=0,total=0;
			DFS(i,head,numperson,total);
			if(numperson>2&&total>k)gang[intstring[head]]=numperson;
		}
	}
	cout<<gang.size()<<endl;
	for(map<string,int>::iterator it=gang.begin();it!=gang.end();it++){
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}
Published 177 original articles · praised 5 · visits 6655

Guess you like

Origin blog.csdn.net/a1920993165/article/details/105559503