试题名称: | 交通规划 |
时间限制: | 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。输入保证每个城市都可以通过铁路达到首都。 |
这个题被坑了,当时考试的时候用二维数组存的图,结果一分没得,后来在别人的博客中看到说数据不保证没有重边,早知道这样用vector去存,最后考了300分真是伤心。回来把代码改成vector就对了,我用的是Dijkstra的方法,没有用堆优化,平常也就是pat的题目经常是Dijkstra,平常刷题一般都是堆优化。我用pre数组来记录当每个点的最短路确定后,每个点是由哪个点过来的,再用另一个vector去存结果,建立一个结果图,最后在结果图中求路径总长度就是最后的结果。
#include <iostream>
#include <cstdio>
#include <algorithm>
#include <vector>
#include <map>
#define inf 0x7f7f7f
using namespace std;
int n,m;
struct node{
int u,w;
};
vector<node>q[10004];
vector<int>p[10004];
int dis[10004];
int vi[10004];
void deal(){
for(int i = 1;i <= n;i++)
dis[i] = inf,vi[i] = 0;
dis[1] = 0;
for(;;){
int minn = inf,temp,f = 0;
for(int i = 1;i <= n;i++){
if(!vi[i]&&dis[i]<minn){
temp = i;
minn = dis[i];
f = 1;
}
}
if(!f)break;
vi[temp] = 1;
for(int i = 0;i < q[temp].size();i++){
if(q[temp][i].w+dis[temp]<dis[q[temp][i].u]&&!vi[q[temp][i].u]){
dis[q[temp][i].u] = q[temp][i].w+dis[temp];
p[q[temp][i].u].clear();
p[q[temp][i].u].push_back(q[temp][i].w);
}
else if(q[temp][i].w+dis[temp]==dis[q[temp][i].u]){
if(q[temp][i].w<p[q[temp][i].u][0]){
p[q[temp][i].u].clear();
p[q[temp][i].u].push_back(q[temp][i].w);
}
}
}
}
int sum = 0;
for(int i = 1;i <= n;i++){
for(int j = 0;j < p[i].size();j++){
sum+=p[i][j];
}
}
printf("%d",sum);
}
int main()
{
scanf("%d%d",&n,&m);
int a,b,c;
for(int i = 0;i < m;i++){
scanf("%d%d%d",&a,&b,&c);
node t;
t.u = b,t.w = c;
q[a].push_back(t);
t.u = a,t.w = c;
q[b].push_back(t);
}
deal();
return 0;
}