-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalmostShortestPath_UVA12144OJ.cpp
131 lines (106 loc) · 2.68 KB
/
almostShortestPath_UVA12144OJ.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
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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
#include <bits/stdc++.h>
using namespace std;
const int inf = INT_MAX / 2;
struct segment
{
int u;
int p;
bool operator < (const segment & temp) const
{
return p > temp.p;
}
};
segment _segment(int u, int p)
{
segment temp{u, p}; return temp;
}
struct edge
{
int u;
int v;
};
edge _edge(int u, int v)
{
edge temp{u, v}; return temp;
}
void erasePath(int u, vector<vector<int>> & a, vector<set<int>> & f)
{
for (auto it = f[u].begin(); it != f[u].end(); ++it)
{
int v = *it;
a[v][u] = inf;
erasePath(v, a, f);
}
}
int main()
{
ios_base::sync_with_stdio(false);
std::cin.tie(NULL);
while (true)
{
int n = 0, m = 0; cin >> n >> m;
if (n + m == 0) break;
vector<vector<int>> a(n, vector<int>(n, inf));
int s, e; cin >> s >> e;
for (int c = 1; c <= m; ++c)
{
int u, v, p; cin >> u >> v >> p;
a[u][v] = p;
}
vector<int> d(n, inf);
priority_queue<segment> pq; pq.push(_segment(s, 0));
vector<set<int>> f(n);
while (pq.empty() == false)
{
segment now = pq.top(); pq.pop();
for (int v = 0; v <= n - 1; ++v)
{
if (a[now.u][v] == inf) continue;
segment next;
next.u = v;
next.p = now.p + a[now.u][v];
if (next.p < d[next.u])
{
d[next.u] = next.p;
f[v].clear();
f[v].insert(now.u);
pq.push(next);
}
else if (next.p == d[next.u])
{
f[v].insert(now.u);
}
}
}
f[s].clear();
erasePath(e, a, f);
vector<int> _d(n, inf);
priority_queue<segment> _pq; _pq.push(_segment(s, 0));
while (_pq.empty() == false)
{
segment now = _pq.top(); _pq.pop();
for (int v = 0; v <= n - 1; ++v)
{
if (a[now.u][v] == inf) continue;
segment next;
next.u = v;
next.p = now.p + a[now.u][v];
if (next.p < _d[next.u])
{
_d[next.u] = next.p;
_pq.push(next);
}
}
}
if (_d[e] == inf)
{
cout << "-1\n";
}
else
{
cout << _d[e] << '\n';
}
}
cout.flush();
return 0;
}