pat a1034 团伙头目【图的深搜】

 题目:

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 threshold 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

给出若干人之间的通话长度(视为无向边),这些通话将他们分为若干组。每个组的总边权设为该组内的所有通话的长度之和,而每个人的点权设为该人参与的通话长度之和。现在给定一个阈值K,且只要一个组的总边权超过K,并满足成员人数超过2,则将该组视为“犯罪团伙(Gang)”,而该组内点权最大的人视为头目。

要求输出“犯罪团伙”的个数,并按头目姓名字典序从小到大的顺序输出每个“犯罪团伙”的头目姓名和成员人数。

二、算法实现

#include<iostream> 
#include<string>
#include<map>
using namespace std;

const int maxn=2010;
const int inf=1000000000;

map<int,string> intToString;
map<string,int> stringToInt;
map<string,int> Gang; 

int G[maxn][maxn]={0};
int weight[maxn]={0};

int n;  //通话记录数量 
int k;  //阈值 
int numPerson=0;  //总人数 

bool vis[maxn]={false};

int change(string str)
{
	if(stringToInt.find(str)!=stringToInt.end())   //能找到 
	{
		return stringToInt[str];
	}
	else  //没有找到 
	{
		stringToInt[str]=numPerson;
		intToString[numPerson]=str;
		//numPerson++;
		return numPerson++;  //骚操作!! 
	}		
}

//nowVisit:当前访问的结点
//head:头目
//numMember: 成员人数
//totalValue:团伙内总的通话时长 
void DFS(int nowVisit,int &head,int &numMember,int &totalValue)
{
	numMember++;
	vis[nowVisit]=true;
	if(weight[nowVisit]>weight[head])
	{
		head=nowVisit;
	} 
	for(int i=0;i<numPerson;i++)
	{
		if(G[nowVisit][i]>0)
		{
			totalValue+=G[nowVisit][i];
			G[nowVisit][i]=G[i][nowVisit]=0;
			if(vis[i]==false)
			{
				DFS(i,head,numMember,totalValue);
			}			
		}
	}	
}

void DFSTrave()
{
	for(int i=0;i<numPerson;i++)
	{
		if(vis[i]==false)
		{
			int head=i;  //老大 
			int numMember=0;  //团伙成员人数 
			int totalValue=0;  //团伙总的通话时长 
			
			DFS(i,head,numMember,totalValue);
			if(numMember>2&&totalValue>k)
			{
				Gang[intToString[head]]=numMember;
			}			
		}		
	}	
}

int main() 
{
	int w;  //通话时长 
	string str1,str2; //通话双方 
	cin>>n>>k;
	for(int i=0;i<n;i++)
	{
		cin>>str1>>str2>>w;
		int id1=change(str1);
		int id2=change(str2); 
		//边读入,边操作 
		weight[id1]+=w;
		weight[id2]+=w;
		G[id1][id2]+=w;
		G[id2][id1]+=w;		
	}
	DFSTrave();	
	cout<<Gang.size()<<endl;
	for(map<string,int>::iterator it=Gang.begin();it!=Gang.end();it++) 
	{
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}

string转int函数

map<int,string> intToString;
map<string,int> stringToInt;
int numPerson=0;  //总人数 

int change(string str)
{
	if(stringToInt.find(str)!=stringToInt.end())   //能找到 
	{
		return stringToInt[str];
	}
	else  //没有找到 
	{
		stringToInt[str]=numPerson;
		intToString[numPerson]=str;
		//numPerson++;
		return numPerson++;  //骚操作!! 
	}		
}

 

### 关于PAT乙级1034题目的解析 对于PAT乙级1034题目——有理数四则运算,此题旨在考察对有理数加减乘除操作的理解以及实现能力。该类问题通常涉及分数的表示方法及其基本运算逻辑的设计。 #### 题目概述 给定两个有理数,执行指定的操作(加法、减法、乘法或除法),并返回简化后的结果。需要注意的是,在处理过程中应当考虑如何有效地化简最终得到的结果,确保分子分母之间不存在公约数[^5]。 #### 示例代码展示 下面是一个简单的Python版本解决方案: ```python from math import gcd def simplify(numerator, denominator): if denominator < 0: numerator *= -1 denominator *= -1 common_divisor = abs(gcd(numerator, denominator)) simplified_numerator = int(numerator / common_divisor) simplified_denominator = int(denominator / common_divisor) return f"{simplified_numerator}/{simplified_denominator}" class RationalNumber: def __init__(self, num, den=1): self.num = num self.den = den @staticmethod def parse(input_str): parts = input_str.split('/') try: num = int(parts[0]) den = int(parts[-1]) or 1 except ValueError as e: raise Exception('Invalid rational number format') from e return RationalNumber(num=num, den=den) def add(self, other): new_num = self.num * other.den + other.num * self.den new_den = self.den * other.den result = simplify(new_num, new_den) return result def subtract(self, other): new_num = self.num * other.den - other.num * self.den new_den = self.den * other.den result = simplify(new_num, new_den) return result def multiply(self, other): new_num = self.num * other.num new_den = self.den * other.den result = simplify(new_num, new_den) return result def divide(self, other): if not isinstance(other, RationalNumber) and other != 0: raise ZeroDivisionError("Cannot divide by zero.") new_num = self.num * other.den new_den = self.den * other.num result = simplify(new_num, new_den) return result if __name__ == "__main__": operation_map = { '+': 'add', '-': 'subtract', '*': 'multiply', '/': 'divide' } expression = "1/2 + (-1/3)" op_index = next((i for i, char in enumerate(expression) if char in "+-*/"), None) first_operand = RationalNumber.parse(expression[:op_index].strip()) second_operand = RationalNumber.parse(expression[op_index+1:].strip()) method_to_call = getattr(first_operand, operation_map.get(expression[op_index])) print(method_to_call(second_operand)) ``` 上述程序定义了一个`RationalNumber`类来封装有理数对象,并实现了四个主要的方法用于完成相应的算术运算。此外还提供了一个辅助函数`simplify()`用来约分化简所得的结果。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值