pat甲级1087 All Roads Lead to Rome (30分)

本文分享了PAT甲级考试中题号为A1087的题目——All Roads Lead to Rome的解题经验。作者指出,该类使用字符串作为顶点构造图的问题在PAT考试中通常不会出现因处理map而导致的时间问题,并分享了自己在43分钟内一次性完成且顺利通过的解题经历。
摘要由CSDN通过智能技术生成

A1087

经验

pat的用字符串作为顶点构图的题似乎都不会卡map的时间(目前没遇到过)。这个题做的比较成功,用时43min,几乎没有调试就过了。

#include <bits/stdc++.h>
using namespace std;

const int N = 205, inf  = 0x3f3f3f3f;
int n, k, id;
map<string, int> s2i;
string i2s[N];
int g[N][N], d[N], h[N], cntRoute[N],cntCity[N], happy[N], pre[N];
bool st[N];

void dijkstra(int u){
	memset(d, 0x3f, sizeof d);
	d[u] = 0;
	cntRoute[u] = 1;
	
	while(true){
		int v = -1;
		for(int i = 0; i < n; i ++){
			if(!st[i] && (v == -1 || d[v] > d[i]))
				v = i;
		}
		
		if(v == -1) break;
		st[v] = true;
		
		for(int i = 0; i < n; i ++){
			if(d[i] > d[v] + g[v][i]){
				d[i] = d[v] + g[v][i];
				pre[i] = v;
				cntCity[i] = cntCity[v] + 1;
				cntRoute[i] = cntRoute[v];
				happy[i] = happy[v] + h[i];
			}
			else if(d[i] == d[v] + g[v][i]){
				if(happy[i] < happy[v] + h[i]){
					pre[i] = v;
					cntCity[i] = cntCity[v] + 1;
					happy[i] = happy[v] + h[i];
				}else if(happy[i] == happy[v] + h[i]){
					if(cntCity[i] > cntCity[v] + 1){
						pre[i] = v;
						cntCity[i] = cntCity[v] + 1;
					}
				}
				cntRoute[i] += cntRoute[v];
			}
		}
	}
	
	return ;
}

void dfs(int u){
	if(u == 0){
		cout << i2s[0];
		return ;
	}
	
	dfs(pre[u]);
	cout << "->" << i2s[u] ;
}


int main(){
	memset(g, 0x3f, sizeof g);
	string ori;
	cin >> n >> k >> ori;
	for(int i = 1; i < n; i++){
		char a[4];
		int tmp;
		scanf("%s %d", a, &tmp);
		s2i[a] = i;
		i2s[i] = a;
		h[i] = tmp;
	}
	id = s2i["ROM"], i2s[0] = ori;
	for(int i = 0; i < k; i++){
		char a[4], b[4];
		int tmp, x, y;
		scanf("%s %s %d", a, b, &tmp);
		x = s2i[a], y = s2i[b];
		g[x][y] = g[y][x] = tmp;
	}
	
	dijkstra(0);

	printf("%d %d %d %d\n", cntRoute[id], d[id], happy[id], happy[id] / cntCity[id]);
	dfs(id);
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值