-
Notifications
You must be signed in to change notification settings - Fork 0
/
AcWing851.cpp
67 lines (67 loc) · 1.26 KB
/
AcWing851.cpp
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
#include <iostream>
#include <queue>
#include <string.h>
using namespace std;
const int N = 100100;
int h[N], e[N], ne[N], w[N];
int n, m, idx;
int dist[N];
bool st[N];
void add(int x, int y, int z)
{
e[idx] = y;
w[idx] = z;
ne[idx] = h[x];
h[x] = idx++;
}
void spfa()
{
memset(dist, 0x3f, sizeof(dist));
dist[1] = 0;
queue<int>q;
for(int i = 1; i <= n; i++)
{
q.push(i);
st[i] = true;
}
while (!q.empty())
{
int t = q.front();
q.pop();
//一定要记住,这里出队 后要记得将其重置为false,因为以后可能还要更新
st[t] = false;
for(int i = h[t]; i != -1; i = ne[i])
{
int v = e[i];
if(dist[v] > dist[t] + w[i])
{
dist[v] = dist[t] + w[i];
if (!st[v])
{
q.push(v);
st[v] = true;
}
}
}
}
if (dist[n] == 0x3f3f3f3f)
{
cout<<"impossible";
}
else
{
cout<<dist[n];
}
}
int main()
{
cin >> n >> m;
int x, y, z;
memset(h, -1, sizeof(h));
for (int i = 0; i < m; i++)
{
cin >> x >> y >> z;
add(x, y, z);
}
spfa();
}