-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathuva-10354.cpp
124 lines (93 loc) · 2.59 KB
/
uva-10354.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
//uva 10354
//Avoiding Your Boss
#include <iostream>
#include <vector>
#include <climits>
#include <map>
#include <set>
using namespace std;
int Dijkstra(vector <map <int, int> > & Graph, vector <int> & path, int source, int destination);
int main(void)
{
int n, e, Bd, Bs, Ys, Yd;
while(cin >> n >> e >> Bs >> Bd >> Ys >> Yd){
--Bd, --Bs, --Ys, --Yd;
vector <map <int, int> > Graph(n);
for(int i = 0; i < e; ++i){
int u, v, d;
cin >> u >> v >> d;
--u, --v;
Graph[u][v] = d;
Graph[v][u] = d;
}
for(int i = 0; i < n; ++i)
Graph[i][i] = 0;
vector <int> bossPath;
vector <int> removeNode;
int bossPathCost = Dijkstra(Graph, bossPath, Bs, Bd);
if(bossPathCost != INT_MAX){//there is a path for boss to get to destination
for(auto a : bossPath)
removeNode.push_back(a);
for(int i = 0; i < bossPath.size() - 1; ++i){
Graph[bossPath[i]].erase(bossPath[i + 1]);
Graph[bossPath[i + 1]].erase(bossPath[i]);
}
while(true){
bossPath.clear();
int cost = Dijkstra(Graph, bossPath, Bs, Bd);
if(cost != bossPathCost)
break;
for(auto a : bossPath)
removeNode.push_back(a);
for(int i = 0; i < bossPath.size() - 1; ++i){
Graph[bossPath[i]].erase(bossPath[i + 1]);
Graph[bossPath[i + 1]].erase(bossPath[i]);
}
}
}
for(auto node : removeNode)
for(int i = 0; i < n; ++i){
Graph[i].erase(node);
Graph[node].erase(i);
}
int yourCost = Dijkstra(Graph, bossPath, Ys, Yd);
if(yourCost == INT_MAX)
cout << "MISSION IMPOSSIBLE." << endl;
else
cout << yourCost << endl;
}
return 0;
}
int Dijkstra(vector <map <int, int> > & Graph, vector <int> & path, int source, int destination)
{
int n = Graph.size();
vector <int> minCost(n, INT_MAX);
vector <int> parent(n, -1);
set <pair <int, int> > currCost;
if(Graph[source].find(source) == Graph[source].end())
return INT_MAX;
else
minCost[source] = Graph[source][source];
currCost.insert(make_pair(minCost[source], source));
while(!currCost.empty()){
int value = currCost.begin()->first;
int node = currCost.begin()->second;
currCost.erase(currCost.begin());
for(auto a : Graph[node])
if(a.second + value < minCost[a.first]){
currCost.erase(make_pair(minCost[a.first], a.first));
minCost[a.first] = a.second + value;
parent[a.first] = node;
currCost.insert(make_pair(minCost[a.first], a.first));
}
}
//making path
path.push_back(destination);
int dst = parent[destination];
while(dst != -1 && parent[dst] != -1){
path.push_back(dst);
dst = parent[dst];
}
path.push_back(source);
return minCost[destination];
}