AcWing 1137. 选择最佳线路

原题链接

考察:最短路

思路:

        类似多源BFS,建立超级源点S,该源点到达所有起点的距离为0.求超级源点到达终点的最短距离.

         这题可以扩展到多起点多终点问题,都是建立超级源点S求解

 1 #include <iostream>
 2 #include <cstring>
 3 #include <vector>
 4 #include <queue>
 5 using namespace std;
 6 const int N = 1010,M = 20010,INF = 0x3f3f3f3f;
 7 typedef pair<int,int> PII;
 8 int h[N],n,m,idx,s,dist[N];
 9 bool st[N];
10 vector<int> node;
11 struct Road{
12     int fr,to,ne,w;
13 }road[M<<1];
14 void add(int a,int b,int w)
15 {
16     road[idx].to = b,road[idx].w = w,road[idx].ne = h[a],h[a] = idx++;
17 }
18 int dijkstra()
19 {
20     priority_queue<PII,vector<PII>,greater<PII> > q;
21     memset(dist,0x3f,sizeof dist);
22     memset(st,0,sizeof st);
23     for(int i=0;i<node.size();i++)
24     {
25         dist[node[i]] = 0;
26         q.push({0,node[i]});
27     }
28     while(q.size())
29     {
30         PII it = q.top();
31         int u = it.second;
32         q.pop();
33         if(st[u]) continue;
34         st[u] = 1;
35         for(int i=h[u];~i;i=road[i].ne)
36         {
37             int v = road[i].to;
38             if(dist[v]>dist[u]+road[i].w)
39             {
40                 dist[v] = dist[u]+road[i].w;
41                 q.push({dist[v],v});
42             }
43         }
44     }
45     if(dist[s]==INF) return -1;
46     else return dist[s];
47 }
48 int main()
49 {
50     while(scanf("%d%d%d",&n,&m,&s)!=EOF)
51     {
52         memset(h,-1,sizeof h);
53         idx = 0;
54         while(m--)
55         {
56             int a,b,c; scanf("%d%d%d",&a,&b,&c);
57             add(a,b,c);
58         }
59         int sz; scanf("%d",&sz);
60         node.clear();
61         for(int i=1;i<=sz;i++)
62         {
63             int x; scanf("%d",&x);
64             node.push_back(x);
65         }
66         int res = dijkstra();
67         printf("%d\n",res);
68     }
69     return 0;
70 }

 

posted @ 2021-04-28 22:45  acmloser  阅读(95)  评论(0编辑  收藏  举报