试题编号: 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。输入保证每个城市都可以通过铁路达到首都。
一个很神奇的错误,用邻接表存图就会TLE,用前向星就不会
下面给出两种方法写的代码
邻接表(80分TLE 100分)
错误原因:双向边数组大小*2
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e6+5;
int h[N],e[N],ne[N],w[N],idx;
int cost[N],dist[N];
bool st[N];
int a,b,c,res=0;
int n,m;
void add(int a,int b,int c){
e[idx]=b;
w[idx]=c;
ne[idx]=h[a];
h[a]=idx++;
}
void dijkstra(){
memset(dist,0x3f,sizeof dist);
dist[1]=0;
priority_queue<PII,vector<PII>,greater<PII>> heap;
heap.push(PII(0, 1));
while(!heap.empty()){
auto t=heap.top();
heap.pop();
int ver=t.second,distance=t.first;
if(st[ver]) continue;
st[ver]=true;
res+=cost[ver];
for(int i=h[ver];i!=-1;i=ne[i]){
int j=e[i];
if(dist[j]>distance+w[i]){
cost[j]=w[i];
dist[j]=distance + w[i];
heap.push(PII(dist[j],j));
}
else if(dist[j]==distance+w[i]&&cost[j]>w[i]){
cost[j]=w[i];
}
}
}
}
int main(){
memset(h,-1,sizeof h);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++){
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
dijkstra();
printf("%d",res);
return 0;
}
前向星(100分)
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e4+5;
int h[N],e[N],ne[N],w[N],idx;
int cost[N],dist[N];
bool st[N];
int a,b,c,res=0;
int n,m;
vector<PII> G[N];
inline int read()
{
int res = 0, f = 1;
char ch;
ch = getchar();
while(!isdigit(ch)){
if(ch == '-')
f = -1;
ch = getchar();
}
while(isdigit(ch)){
res = res * 10 + ch - '0';
ch = getchar();
}
return f * res;
}
void add(int a,int b,int c){
e[idx]=b;
w[idx]=c;
ne[idx]=h[a];
h[a]=idx++;
}
void dijkstra(){
memset(dist,0x3f3f3f3f,sizeof dist);
dist[1]=0;
priority_queue<PII,vector<PII>,greater<PII> > heap;
heap.push(PII(0, 1));
while(!heap.empty()){
PII t=heap.top();
heap.pop();
int ver=t.second,distance=t.first;
if(st[ver])
continue;
st[ver] = 1;
for(int i = 0; i < G[ver].size(); i ++){
int j=G[ver][i].first;
int w = G[ver][i].second;
if(st[j])
continue;
if(dist[j]>distance+w){
dist[j]=distance + w;
heap.push(PII(dist[j],j));
cost[j]=w;
}
else if(dist[j] == distance+w)
cost[j] = min(cost[j], w);
}
}
}
int main(){
memset(h,-1,sizeof h);
scanf("%d%d",&n,&m);
for(int i=1;i<=m;i++){
a = read(), b = read(), c = read();
G[a].push_back(PII(b, c));
G[b].push_back(PII(a, c));
}
dijkstra();
int ans = 0;
for(int i = 2; i <= n; i ++)
ans += cost[i];
cout << ans << endl;
return 0;
}