![](https://i-blog.csdnimg.cn/blog_migrate/14055f27204a6c5f08e351cd09fc4c6d.png)
输入样例:
7 7
1 2 5
1 4 3
2 3 2
2 5 1
3 6 7
5 6 8
6 7 6
3
7
5
4
7
1
2
3
4
5
6
7
输出样例:
3
1
3
0
0
6
0
题意:给一个有n个点和m条带权边的无向图,图中共有k个商店,问这些点去最近的商店的距离
思路:堆优化的迪杰斯特拉,用一个点连接所有商店,并且边权设为0,这样相当于每个商店都是起点,就可以算出从商店到各个点的最短距离。
![](https://i-blog.csdnimg.cn/blog_migrate/cae47b9ee1a82b681fff500a9b737b15.png)
代码1(邻接表):
#include<bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
const int N = 1e5 + 5;
int n, m, k, d[N];
struct node{
int to, w;
};
vector<node> v[N];
void dij(){
memset(d, 127, sizeof(d));
d[n + 1] = 0;
priority_queue<pii, vector<pii>, greater<pii> > q;
q.push({0, n + 1});
while(!q.empty()){
pii p = q.top();
q.pop();
int sec = p.second;
for(int i = 0; i < v[sec].size(); i++){
node e = v[sec][i];
if(d[e.to] > d[sec] + e.w){
d[e.to] = d[sec] + e.w;
q.push({d[e.to], e.to});
}
}
// printf("***%d %d\n", d[sec], sec);
}
}
int main(){
cin >> n >> m;
for(int i = 1; i <= m; i++){
int x, y, w; cin >> x >> y >> w;
v[x].push_back({y, w});
v[y].push_back({x, w});
}
cin >> k;
for(int i = 1; i <= k; i++){
int x; cin >> x;
v[n + 1].push_back({x, 0});
}
dij();
int q; cin >> q;
while(q--){
int x; cin >> x;
printf("%d\n", d[x]);
}
}
代码2(链式前向星):
好像会快一点
#include<bits/stdc++.h>
#define pii pair<int, int>
using namespace std;
const int N = 3e5 + 5;
int n, m, k, d[N], vis[N];
int h[N], ne[N], w[N], e[N], idx;
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, 127, sizeof(d));
d[n + 1] = 0;
priority_queue<pii, vector<pii>, greater<pii> > q;
q.push({0, n + 1});
while(!q.empty()){
pii p = q.top();
q.pop();
int sec = p.second;
if(vis[sec]) continue;
vis[sec] = 1;
for(int i = h[sec]; i != -1; i = ne[i]){
int j = e[i];
if(d[j] > d[sec] + w[i]){
d[j] = d[sec] + w[i];
q.push({d[j], j});
}
}
}
}
int main(){
scanf("%d%d", &n, &m);
memset(h, -1, sizeof(h));
for(int i = 1; i <= m; i++){
int x, y, w; scanf("%d%d%d", &x, &y, &w);
add(x, y, w);
add(y, x, w);
}
cin >> k;
for(int i = 1; i <= k; i++){
int x; scanf("%d", &x);
add(n + 1, x, 0);
}
dij();
int q; scanf("%d", &q);
while(q--){
int x; scanf("%d", &x);
printf("%d\n", d[x]);
}
}