最短路变形情景一
dijkstra只能解决单源最短路的问题,多起点要跑多次dijkstra算法或者spfa?不不不,其实还有更好的思路,把这些多起点都连接同一个无关紧要的点s,让这些多起点到s的距离是0,最后在跑dijkstra求s到n的最短路,这样就转化成单源最短路径了
#include <iostream>
#include <algorithm>
#include <cstring>
#include <queue>
#include <cstdio>
#include <vector>
using namespace std;
struct edge{
int to,w;
edge(int a,int b){
to = a;w = b;
}
};
struct Node{
int k,step;
Node(int a,int b){
k = a;step = b;
}
bool operator <(const Node &s)const{
return s.step < step;
}
};
const int maxn = 1005;
const int inf = 1e7;
vector<edge>e[maxn];
int n,m,s;
int dijkstra()
{
priority_queue<Node>q;
int dist[n+5],visited[n+5];
for(int i = 0;i <= n;i++){
dist[i] = inf;
visited[i] = 0;
}
int x = 0;
dist[x] = 0;
q.push(Node(x,dist[0]));
while(!q.empty()){
Node p = q.top();
q.pop();
if(visited[p.k]){
continue;
}
visited[p.k] = 1;
for(int i = 0;i < e[p.k].size();i++){
edge t = e[p.k][i];
if(visited[t.to]){
continue;
}
if(dist[t.to] > dist[p.k] + t.w){
dist[t.to] = dist[p.k] + t.w;
q.push(Node(t.to,dist[t.to]));
}
}
}
if(dist[s] == inf){
printf("-1\n");
}
else{
printf("%d\n",dist[s]);
}
}
int main()
{
while(~scanf("%d%d%d",&n,&m,&s)){
for(int i = 0; i <= n;i++){
e[i].clear();
}
while(m--){
int x,y,z;
scanf("%d%d%d",&x,&y,&z);
e[x].push_back(edge(y,z));
}
int k,ans = inf;
scanf("%d",&k);
while(k--){
int x;
scanf("%d",&x);
e[0].push_back(edge(x,0));
}
dijkstra();
}
return 0;
}
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdio>
#include<queue>
#include<vector>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 1005;
struct node{
int k,step;
node(int a,int b){
k = a;step = b;
}
bool operator <(const node &s)const{
return step > s.step;
}
};
struct edge{
int from,to,w;
edge(int a,int b,int c){
from = a;to = b;w = c;
}
};
vector<edge>e[maxn];
bool visited[maxn];
int dist[maxn];
priority_queue<node>q;
void dijkstra()
{
visited[0] = false;
for(int i = 1;i <= maxn;i++){
dist[i] = inf;
visited[i] = false;
}
while(!q.empty()){
q.pop();
}
int x = 0;
dist[x] = 0;
q.push(node(x,0));
while(!q.empty()){
node p = q.top();
q.pop();
if(visited[p.k]){
continue;
}
visited[p.k]=true;
for(int i = 0;i < e[p.k].size();i++){
edge t = e[p.k][i];
if(!visited[t.to] && dist[t.to] > dist[p.k] + t.w){
dist[t.to] = dist[p.k] + t.w;
q.push(node(t.to,dist[t.to]));
}
}
}
}
int main()
{
int t,s,d;
while(scanf("%d%d%d",&t,&s,&d)!=EOF){
for(int i = 0;i < maxn;i++){
e[i].clear();
}
int x,y,z;
for(int i = 1;i <= t;i++){
scanf("%d%d%d",&x,&y,&z);
e[x].push_back(edge(x,y,z));
e[y].push_back(edge(y,x,z));
}
for(int i = 0;i < s;i++){
scanf("%d",&x);
e[0].push_back(edge(0,x,0));
e[x].push_back(edge(x,0,0));
}
dijkstra();
int ans = inf;
for(int i = 0;i < d;i++){
scanf("%d",&x);
ans = min(ans,dist[x]);
}
printf("%d\n",ans);
}
return 0;
}