AcWing 1137. 选择最佳线路
解题思路:每个起点都跑一次最短路会超时,那就建立一个虚拟初始点,这个初始点距离所有起点的距离都是0,所以这个虚拟初始点到终点的最短路径就是所有起点中最短的最短路
#include<bits/stdc++.h>
using namespace std;
const int N = 1010, M = 40010, INF = 0x3f3f3f3f;
int n, m, T;
int h[N], e[M], ne[M], w[M], idx;
int d[N];
int q[N];
bool st[N];
void add(int a, int b, int c){
e[idx] = b;
w[idx] = c;
ne[idx] = h[a];
h[a] = idx ++ ;
}
int spfa(){
memset(d, 0x3f, sizeof d);
int hh = 0, tt = 1;
q[0] = 0;
d[0] = 0;
st[0] = true;
while(tt != hh){
int t = q[hh ++ ];
if(hh == N) hh = 0;
st[t] = false;
for(int i = h[t]; ~i; i = ne[i]){
int j = e[i];
if(d[j] > d[t] + w[i]){
d[j] = d[t] + w[i];
if(!st[j]){
q[tt ++ ] = j;
if(tt == N) tt = 0;
st[j] = true;
}
}
}
}
if(d[T] > 1e9) return -1;
else return d[T];
}
int main()
{
while(scanf("%d%d%d", &n, &m, &T) != -1){
memset(h, -1, sizeof h);
idx = 0;
while(m -- ){
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
}
int w;
cin>>w;
while(w -- ){
int ver;
scanf("%d", &ver);
add(0, ver, 0);
}
cout<<spfa()<<endl;
}
return 0;
}