CCF---201609-4---交通规划---C++----SPFA

6 篇文章 0 订阅
5 篇文章 0 订阅

试题编号:201609-4
试题名称:交通规划
时间限制:1.0s
内存限制:256.0MB

问题描述:

问题描述
  G国国王来中国参观后,被中国的高速铁路深深的震撼,决定为自己的国家也建设一个高速铁路系统。
  建设高速铁路投入非常大,为了节约建设成本,G国国王决定不新建铁路,而是将已有的铁路改造成高速铁路。现在,请你为G国国王提供一个方案,将现有的一部分铁路改造成高速铁路,使得任何两个城市间都可以通过高速铁路到达,而且从所有城市乘坐高速铁路到首都的最短路程和原来一样长。请你告诉G国国王在这些条件下最少要改造多长的铁路。
  
输入格式
  输入的第一行包含两个整数n, m,分别表示G国城市的数量和城市间铁路的数量。所有的城市由1到n编号,首都为1号。
  接下来m行,每行三个整数a, b, c,表示城市a和城市b之间有一条长度为c的双向铁路。这条铁路不会经过a和b以外的城市。
  
输出格式
  输出一行,表示在满足条件的情况下最少要改造的铁路长度。
  
样例输入

4 5
1 2 4
1 3 5
2 3 2
2 4 3
3 4 2

样例输出

11

评测用例规模与约定
  对于20%的评测用例,1 ≤ n ≤ 10,1 ≤ m ≤ 50;
  对于50%的评测用例,1 ≤ n ≤ 100,1 ≤ m ≤ 5000;
  对于80%的评测用例,1 ≤ n ≤ 1000,1 ≤ m ≤ 50000;
  对于100%的评测用例,1 ≤ n ≤ 10000,1 ≤ m ≤ 100000,1 ≤ a, b ≤ n,1 ≤ c ≤ 1000。输入保证每个城市都可以通过铁路达到首都。

实现思路

有坑的最短路劲问题,再SPFA判断中加一个==判断,把最短边留下。

实现代码

#include<iostream>
#include<queue>
#include<cstring>

using namespace std;

const int maxn = 10000 + 5;
const int maxm = 100000 + 5;

struct Edge {
	int to, next, length;
}edges[maxm << 1];

int dis[maxn];		//存最短路径长度
int inq[maxn];		//判断是否在栈中
int ans[maxn];		//存构成最短路径的边,且此边也该是相同长度路径的最短边
int head[maxn];		//链式前向星的头
int cnt = 0;	

void Link(int from, int to, int length) {	//链式前向星
	edges[++cnt].to = to;
	edges[cnt].length = length;
	edges[cnt].next = head[from];
	head[from] = cnt;
}

void spfa() {
	memset(inq, 0, sizeof(inq));
	memset(dis, 0x3f, sizeof(dis));
	queue<int> q;
	q.push(1);
	dis[1] = 0;
	inq[1] = 1;
	while (q.size()) {
		int now = q.front();
		q.pop();
		inq[now] = 0;
		for (int i = head[now]; i; i = edges[i].next) {
			int to = edges[i].to, len = edges[i].length;
			if (dis[to] > dis[now] + len) {
				dis[to] = dis[now] + len;
				ans[to] = len;
				if (!inq[to]) {
					inq[to] = 1;
					q.push(to);
				}
			}
			else if (dis[to] == dis[now] + len) ans[to] = min(ans[to],len);		//此处乃坑
		}
	}
}

int main() {
	int n, m, a, b ,c, output = 0;
	cin >> n >> m;
	while (m--) {
		cin >> a >> b >> c;
		Link(a, b, c);
		Link(b, a, c);
	}
	spfa();
	for (int i = 2; i <= n; i++) output += ans[i];	//将所有边加起来
	cout << output << endl;
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值