分析:这道题原本的思路是,把每一个起点都进行一边dij,这样肯定会超时的,那么引入虚拟源点,就是在每一个起点前,再连一个源点,源点到起点的距离为0;
代码
#include<iostream>
#include<cstring>
#include<queue>
using namespace std;
typedef pair<int,int> PII;
const int N = 1e5 + 10,M = 3e5 + 10;
int e[M],ne[M],w[M],h[N],idx;
int d[N];
bool st[N];
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 dij()
{
memset(d,0x3f,sizeof d);
priority_queue<PII,vector<PII>,greater<PII>> heap;
d[0]=0;
heap.push({0,0});
while(heap.size())
{
auto t=heap.top();
heap.pop();
int ver=t.second;
if(st[ver]) continue;
st[ver]=true;
for(int i=h[ver];~i;i=ne[i])
{
int j=e[i];
if(d[j]>d[ver]+w[i])
{
d[j]=d[ver]+w[i];
heap.push({d[j],j});
}
}
}
}
int main()
{
memset(h,-1,sizeof h);
scanf("%d%d",&n,&m);
while(m--)
{
int a,b,c;
scanf("%d%d%d",&a,&b,&c);
add(a,b,c);
add(b,a,c);
}
int k;
cin>>k;
while(k--)
{
int x;
scanf("%d",&x);
add(0,x,0);//虚拟源点的建立
}
dij();
int q;
cin>>q;
while(q--)
{
int x;
scanf("%d",&x);
printf("%d\n",d[x]);
}
return 0;
}