您的位置:首页 > 其它

CCF 2016 09-4 修高铁 最短路径+最小生成树

2017-09-16 22:41 459 查看
问题描述
  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

思路:这道题将最短路径和最小生成树结合起来。因为要保持每个城市到首都的最短距离,所以要在dijkstra的基础上找到最小生成树。每次更新最新点v的相邻点temp时,更新它的最小花费cost。d[temp.second]>d[v]+temp.first时,一定更新花费,因为要在最短路径的基础上满足。相等的时候,取最小花费。
#include<iostream>
#include<vector>
#include<algorithm>
#include<string.h>
#include<queue>
using namespace std;
#define maxv 10000+5
typedef  pair<int,int> P;
int d[maxv], cost[maxv]; bool visit[maxv];
vector<P>G[maxv];
#define INF 1<<29
int V;
struct cmp
{
bool operator()(P x,P y)
{
return x.first > y.first;
}
};
int dijkstra(int s)
{
priority_queue<P, vector<P>, cmp>Q;
fill(d, d + V + 1, INF);
fill(cost, cost + V + 1, INF);
fill(visit, visit + V + 1, 0);
d[s] = 0; cost[s] = 0;
Q.push(P(d[s], s)); P temp,temp2;
while (Q.size())
{
temp = Q.top();
Q.pop();
int v = temp.second;
if (!visit[v])
{
visit[v] = 1;
for (int i = 0; i < G[v].size(); i++)
{
temp2 = G[v][i];
if (visit[temp2.second])
continue;

if (d[temp2.second] > d[v] + temp2.first)
{
d[temp2.second] = d[v] + temp2.first;
Q.push(P(d[temp2.second], temp2.second));
cost[temp2.second] = temp2.first;//
}
else if (d[temp2.second] == d[v] + temp2.first)//
cost[temp2.second] = min(cost[temp2.second], temp2.first);//和普通dijkstra不一样的地方,计算最小生成树
}
}
}
int ans = 0;
for (int i = 2; i <= V; i++)
ans += cost[i];//计算到每个点的花费
return ans;
}
int main()
{
int M,a,b,c;
cin >> V >> M;
while (M--)
{
cin >> a >> b >> c;
G[a].push_back(P(c, b));
G[b].push_back(P(c, a));
}
cout << dijkstra(1);
system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  dijkstra ccf