【图论之单源最短路】单源最短路专题(Dijkstra,SPFA)
超级(虚拟)源点类型
1488. 最短距离(超级源点)
建立超级源点,从超级源点向某些点连一条权值为0的单向边
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
using namespace std;
typedef pair<int, int> PII;
const int N = 1e5 + 10, M = 1e5 * 2 + 1e5 + 10; //无向边*2,再加1e5个超级源点连向其他点的边
int n, m;
int dist[N], id[N];
int h[N], w[M], e[M], ne[M], idx;
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 dijkstra()
{
//如果是多次调用dijkstra(),则要每次清空st数组,本题只调用一次,可以不写
//memset(st, 0, sizeof st);
memset(dist, 0x3f, sizeof dist);
dist[0] = 0;
priority_queue<PII, vector<PII>, greater<PII>> heap;
heap.push({0, 0});
while (heap.size())
{
PII t = heap.top();
heap.pop();
int ver = t.second, distance = t.first;
if (st[ver]) continue;
st[ver] = true;
for (int i = h[ver]; i != -1; i = ne[i])
{
int j = e[i];
if (dist[j] > distance + w[i])
{
dist[j] = distance + w[i];
heap.push({dist[j], j});
}
}
}
}
int main()
{
scanf("%d%d", &n, &m);
memset(h, -1, sizeof h);
while (m -- )
{
int a, b, c;
scanf("%d%d%d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
int k;
scanf("%d", &k);
while (k -- )
{
int id;
scanf("%d", &id);
add(0, id, 0); // 超级源点向这些点连一条权值为0的边
}
dijkstra();
int Q;
scanf("%d", &Q);
while (Q -- )
{
int ver;
scanf("%d", &ver);
printf("%d\n", dist[ver]);
}
return 0;
}
作者:NFYD
链接:https://www.acwing.com/activity/content/code/content/6289271/
来源:AcWing
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。