-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhighways_dijkstra.cpp
161 lines (126 loc) · 2.59 KB
/
highways_dijkstra.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
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
#include <iostream>
#include <vector>
#include <climits>
#include <algorithm>
#include <queue>
using namespace std;
struct node {
int vertex;
int edge_length;
node* next;
node() {
next = NULL;
}
};
bool fn( int x ) {
if ( x != LLONG_MAX ) {
return true;
} else {
return false;
}
}
typedef pair<long long int, int> pl;
class graph {
int v;
int e;
vector<node*> arr;
priority_queue<pl, vector<pl>, greater<pl> > Q;
public :
vector<long long int> distance;
void insert( int v1, int v2, int e ) {
node* head = arr[v1];
node *tmp = head;
if ( head == NULL ) {
arr[v1] = new node;
arr[v1]->vertex = v2;
arr[v1]->edge_length = e;
return;
}
while ( tmp -> next != NULL ) {
tmp = tmp -> next;
}
tmp -> next = new node;
tmp -> next ->vertex = v2;
tmp -> next ->edge_length = e;
return;
}
long long int dijkstra(int src, int dsn ) {
pair<long long int, int> a;
a.first = 0;
a.second = src;
Q.push(a);
int vtx = 0;
while ( !Q.empty() ) {
vtx = Q.top().second;
if ( distance[vtx] >= Q.top().first ) {
distance[vtx] = Q.top().first;
Q.pop();
if ( vtx == dsn ) {
return distance[vtx];
}
node* tmp = arr[vtx];
while ( tmp != NULL ) {
if ( distance[vtx] + tmp->edge_length < distance[tmp->vertex] && distance[vtx] != LLONG_MAX) {
pair<long long int, int> mod;
distance[tmp->vertex] = distance[vtx] + tmp->edge_length;
mod.second = tmp->vertex;
mod.first = distance[tmp->vertex];
Q.push(mod);
}
tmp = tmp -> next;
}
} else {
Q.pop();
}
}
return distance[dsn];
}
void print_graph() {
for ( int i = 0; i < v; i++ ) {
node* tmp = arr[i];
cout << " vertex " << i << " ";
while ( tmp != NULL ) {
cout << tmp -> vertex << " -> ";
tmp = tmp -> next;
}
cout << endl;
}
}
graph(int v, int e) {
for ( int i = 0; i < v; i++ ) {
arr.push_back(NULL);
distance.push_back(LLONG_MAX);
}
this -> v = v;
this -> e = e;
}
};
int main()
{
int t;
cin >> t;
for ( int j = 0; j < t; j++ ) {
int v, e;
cin >> v;
cin >> e;
int src, dsn;
cin >> src;
cin >> dsn;
graph cities(v, e);
for ( int i = 0; i < e; i++ ) {
int v1, v2, e;
cin >> v1;
cin >> v2;
cin >> e;
cities.insert(v1 - 1, v2 -1, e );
cities.insert(v2 - 1, v1 -1, e );
}
long long int sol = cities.dijkstra(src - 1, dsn - 1);
if ( sol != LLONG_MAX ) {
cout << sol << endl;
} else {
cout << "NONE" << endl;
}
}
return 0;
}