Luo Gu P1339 heat wave [shortest]

Topic : https://www.luogu.org/problemnew/show/P1339

Meaning of the questions : Given a map, ask the shortest beginning to the end.

Ideas : dijkstra board title.

Long time no write most short-circuited. Step dijkstra's summarize it.

d represents the current array for the shortest path, vis array to mark whether the current point is already set in the shortest.

Each time find a minimum of node d, he said he has been unable to shorter and took him to the collection, use him to update the other nodes. We made a total of n-1 times.

 1 #include<cstdio>
 2 #include<cstdlib>
 3 #include<map>
 4 #include<set>
 5 #include<cstring>
 6 #include<algorithm>
 7 #include<vector>
 8 #include<cmath> 
 9 #include<stack>
10 #include<queue>
11 #include<iostream>
12 
13 #define inf 0x3f3f3f3f
14 using namespace std;
15 typedef long long LL;
16 typedef pair<int, int> pr;
17 
18 int t, c, ts, te;
19 const int maxn = 2500;
20 const int maxm = 6205;
21 struct edge{
22     int to, nxt, cost;
23 }e[maxm * 2];
24 int head[maxn], tot;
25 
26 void add(int x, int y, int w)
27 {
28     e[++tot].to = y;
29     e[tot].cost = w;
30     e[tot].nxt = head[x];
31     head[x] = tot;
32     e[++tot].to = x;
33     e[tot].cost = w;
34     e[tot].nxt = head[y];
35     head[y] = tot;
36 }
37 
38 bool vis[maxn];
39 int d[maxn]; 
40 void dijkstra()
41 {
42     memset(d, 0x3f, sizeof(d));
43     for(int i = head[ts]; i; i = e[i].nxt){
44         d[e[i].to] = e[i].cost;
45     }
46     vis[ts] = true;
47     d[ts] = 0;
48     for(int i = 1; i < t; i++){
49         int min = inf, min_id;
50         for(int j = 1; j <= t; j++){
51             if(d[j] < min && !vis[j]){
52                 min = d[j];
53                 min_id = j;
54             }
55         }
56         vis[min_id] = true;
57         for(int i = head[min_id]; i; i = e[i].nxt){
58             if(d[e[i].to] > min + e[i].cost){
59                 d[e[i].to] = min + e[i].cost;
60             }
61         }
62     }
63 }
64 
65 int main()
66 {
67     scanf("%d%d%d%d", &t, &c, &ts, &te);
68     for(int i = 0; i < c; i++){
69         int rs, re, ci;
70         scanf("%d%d%d", &rs, &re, &ci);
71         add(rs, re, ci);
72     }
73     
74     dijkstra();
75     printf("%d\n", d[te]);
76 }

 

Guess you like

Origin www.cnblogs.com/wyboooo/p/11088157.html