PAT A1034

本文介绍了一种使用深度优先搜索(DFS)进行图遍历的方法,该方法用于寻找符合特定条件的连通分量,包括节点数量超过两个且权重总和大于给定阈值的分量。文章详细展示了如何通过C++实现这一算法,并处理了大型数据集中的大量唯一标识符。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

方法:用深度遍历,同时计算每个连通分量的结点数,及点权最大的结点。

注意点:1,输出的连通分量要求,结点数>2且点权之和大于指定值;2,题中有至多1000个记录,但至多会有2000个不同的名字。

#include <iostream>
#include <string>
#include <map>
#include <vector>
#include <algorithm>
using namespace std;
const int maxn=2010;
map<string,int> mp;
map<int,string> mp2;  //数字到名字的映射 
vector<int> child[maxn];
int N,K,weight[maxn]={0},index=0;  //index记录所有电话记录包含的人数 

map<string,int> gang; 
bool vis[maxn]={0};
void DFS(int v,int &num,int &headindex,int &sumw,int &maxw){
	vis[v]=true;
	num++;
	sumw+=weight[v];
	if(weight[v]>maxw){
		headindex=v;
		maxw=weight[v];
	}
	for(int i=0;i<child[v].size();i++){
		if(vis[child[v][i]]==false){
			DFS(child[v][i],num,headindex,sumw,maxw);
		}
	}
}
void DFStrav(){
	int numgang=0;
	for(int i=0;i<index;i++){
		if(vis[i]==false){
			int num=0,headindex=-1,sumw=0,maxw=-1;
			DFS(i,num,headindex,sumw,maxw);
			if(num<=2||sumw<=2*K) continue;
			gang[mp2[headindex]]=num;
			numgang++;
		}
	}
	printf("%d\n",numgang);
}
int main(){
	scanf("%d%d",&N,&K);
	string s1,s2;
	int time;
	for(int i=0;i<N;i++){
		cin>>s1>>s2>>time;
		if(mp.find(s1)==mp.end()){
			mp[s1]=index++;
			mp2[index-1]=s1;
		}
		weight[mp[s1]]+=time;
		if(mp.find(s2)==mp.end()){
			mp[s2]=index++;
			mp2[index-1]=s2;
		}
		weight[mp[s2]]+=time;
		child[mp[s1]].push_back(mp[s2]);
		child[mp[s2]].push_back(mp[s1]);
	}
	DFStrav();
	for(map<string,int>::iterator it=gang.begin();it!=gang.end();it++){
		cout<<it->first<<" "<<it->second<<endl;
	}
	return 0;
}


### 关于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、付费专栏及课程。

余额充值