forked from sdssudhu/SPOJ
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSAMERA08A.cpp
More file actions
146 lines (112 loc) · 3.08 KB
/
Copy pathSAMERA08A.cpp
File metadata and controls
146 lines (112 loc) · 3.08 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
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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
// Almost Shortest Path
#include<bits/stdc++.h>
using namespace std;
const int inf = (1 << 30) - 1;
vector < vector < int > > graph;
vector < vector < int > > paths;
vector < int > vi;
int adjm[501][501];
int n, m, start, finish;
void dijkstra()
{
set < pair < int, int > > ordered;
ordered.insert(make_pair(0, start));
vector < int > dist(n, inf);
dist[start] = 0;
int node, cost;
while (!ordered.empty())
{
cost = (*ordered.begin()).first;
node = (*ordered.begin()).second;
ordered.erase(ordered.begin());
for (int i = 0; i < graph[node].size(); i++)
{
int newn = graph[node][i];
int newc = adjm[node][newn];
if (cost + newc <= dist[newn])
{
if (cost + newc < dist[newn])
{
paths[newn].clear();
}
paths[newn].push_back(node);
if (dist[newn] != inf)
{
ordered.erase(make_pair(dist[newn], newn));
}
dist[newn] = cost + newc;
ordered.insert(make_pair(dist[newn], newn));
}
}
}
}
void removeroads(int node)
{
for (int i = 0; i < paths[node].size(); i++)
{
int neigh = paths[node][i];
adjm[neigh][node] = -1;
removeroads(neigh);
}
}
int dijkstra2()
{
set < pair < int, int > > ordered;
ordered.insert(make_pair(0, start));
vector < int > dist(n, inf);
dist[start] = 0;
int node, cost;
while (!ordered.empty())
{
cost = (*ordered.begin()).first;
node = (*ordered.begin()).second;
if (node == finish)
{
return cost;
}
ordered.erase(ordered.begin());
for (int i = 0; i < graph[node].size(); i++)
{
int newn = graph[node][i];
int newc = adjm[node][newn];
if (newc == -1) continue; // path is deleted
if (cost + newc < dist[newn])
{
if (dist[newn] != inf)
{
ordered.erase(make_pair(dist[newn], newn));
}
dist[newn] = cost + newc;
ordered.insert(make_pair(dist[newn], newn));
}
}
}
return -1;
}
int main()
{
while (true)
{
scanf("%d %d", &n, &m);
if (n + m == 0)
{
return 0;
}
scanf("%d %d", &start, &finish);
graph.insert(graph.begin(), n, vi);
paths.insert(paths.begin(), n, vi);
int a, b, c;
for (int i = 0; i < m; i++)
{
scanf("%d %d %d", &a, &b, &c);
graph[a].push_back(b);
adjm[a][b] = c;
}
dijkstra();
removeroads(finish);
printf("%d\n", dijkstra2());
graph.clear();
paths.clear();
}
return 0;
}