-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathspfa.cpp
More file actions
97 lines (80 loc) · 1.34 KB
/
Copy pathspfa.cpp
File metadata and controls
97 lines (80 loc) · 1.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
#include <iostream>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int MAXN = 100005;
const int INF = 1e6;
struct Edge{
int from, to, dist;
Edge(){};
Edge(int f, int t, int d):from(f), to(t), dist(d){};
};
vector<int> G[MAXN];
vector<Edge> edges;
int myRank[MAXN], dis[MAXN];
bool inque[MAXN];
void init(int n)
{
for(int i = 0; i <= n; i++)
G[i].clear();
edges.clear();
}
void add(int u, int v, int w)
{
edges.push_back(Edge(u, v, w));
int m = edges.size();
G[u].push_back(m - 1);
}
int spfa(int s, int n)
{
for(int i = 0; i <= n; i++)
{
dis[i] = INF;
myRank[i] = 0;
inque[i] = false;
}
dis[s] = 0;
myRank[s] = 1;
queue<int> que;
inque[s] = true;
que.push(s);
while(!que.empty())
{
int u = que.front();
inque[u] = false;
que.pop();
for(int i = 0; i < (int)G[u].size(); i++)
{
Edge e = edges[G[u][i]];
if(dis[e.to] > dis[u] + e.dist)
{
dis[e.to] = dis[u] + e.dist;
if(!inque[e.to])
{
que.push(e.to);
inque[e.to] = true;
myRank[e.to] ++;
if(myRank[e.to] >= n) return false;
}
}
}
}
return true;
}
int main()
{
int n, m, s, t, a, b, c;
scanf("%d %d %d %d", &n, &m, &s, &t);
init(n);
while(m --)
{
scanf("%d %d %d", &a, &b, &c);
add(a, b, c);
add(b, a, c);
}
spfa(s, n);
printf("%d\n", dis[t]);
return 0;
}