交通规划(csp201609-4) :
问题描述
题目简述
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算法求出单源最短路。但是,这个题的答案是求改造道路的最短长度,且每两个城市之间都需要有一条改造道路。这样就是在最短路的前提下,每个城市都改造到它的最短前驱路径即可。最后的答案是所有最短前驱路径的和。最短前驱路径可以在dijkstra算法运行时得出。总之还是一个dijkstra的常规问题,但是稍微有些变形。
参考代码
#include <iostream>
#include <queue>
#include <vector>
#include <cstring>
using namespace std;
const int inf=300000005;
class edge
{
public:
int from;
int to;
int weight;
edge(int uu,int vv,int ww)
{
from=uu;
to=vv;
weight=ww;
}
};
class heapnode
{
public:
int index;
int path_length;
heapnode(int id,int len)
{
index=id;
path_length=len;
};
bool operator <(const heapnode& h) const
{
return path_length>h.path_length;
}
};
vector<edge> edges;
priority_queue<heapnode> pq;
vector<int> points[10010];
int vis[10010];
int path[10010];
int cnt[10010];
int n,m;
void init()
{
memset(vis,0,sizeof(vis));
memset(cnt,-1,sizeof(cnt));
edges.clear();
while(!pq.empty()) pq.pop();
for(int i=0;i<10010;i++)
{
points[i].clear();
path[i]=inf;
}
}
void addedge(int u,int v,int w)
{
edge e1(u,v,w);
edges.push_back(e1);
points[u].push_back(edges.size()-1);
edge e2(v,u,w);
edges.push_back(e2);
points[v].push_back(edges.size()-1);
}
int dijkstra()
{
heapnode nh(1,0);
path[1]=0;
cnt[1]=0;
pq.push(nh);
int count=1;
while(count<n)
{
heapnode th=pq.top();
pq.pop();
if(vis[th.index]==1) continue;
vis[th.index]=1;
count++;
for(int i=0;i<points[th.index].size();i++)
{
int edge_id=points[th.index][i];
int path_len=path[th.index]+edges[edge_id].weight;
if(path[edges[edge_id].to]>path_len)
{
path[edges[edge_id].to]=path_len;
cnt[edges[edge_id].to]=edges[edge_id].weight;
heapnode hh(edges[edge_id].to,path_len);
pq.push(hh);
}
else if(path[edges[edge_id].to]==path_len)
{
cnt[edges[edge_id].to]=min(cnt[edges[edge_id].to],edges[edge_id].weight);
}
}
}
int ans=0;
for(int i=1;i<=n;i++)
{
ans+=cnt[i];
}
return ans;
}
int main()
{
init();
scanf("%d %d",&n,&m);
for(int i=1;i<=m;i++)
{
int a,b,c;
scanf("%d %d %d",&a,&b,&c);
addedge(a,b,c);
}
printf("%d",dijkstra());
return 0;
}
心得体会
还是比较顺利的做出来了,之前审题的时候差点以为是每个点到首都至少有一条高速路。然后就绕进去了。最后重新看了一遍题才明白过来原来挺常规的。总之还是要认真读题。最后,也是dijkstra的模板练习题吧,感觉还可以。