-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBidirectional_dijkstra.cpp
108 lines (94 loc) · 1.89 KB
/
Bidirectional_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
#include <bits/stdc++.h>
using namespace std;
typedef pair<int,int> ii;
typedef vector<int> vi;
typedef vector< ii > vii;
#define INF 1e9
int V,E,res(INT_MAX);
vector< vii > g;
vector< vii > gr;
vi df;
vi db;
void dijkstra(int s, int t)
{
df[s]=0;
db[t]=0;
set<int> p;
priority_queue< ii, vector< ii >, greater<ii> > pqf; pqf.push(ii(0,s));
//Backward graph priority queue
priority_queue< ii, vector< ii >, greater<ii> > pqb; pqb.push(ii(0,t));
while(1)
{
//dijkstra on forward graph
ii ff = pqf.top(); pqf.pop();
int d(ff.first), u(ff.second);
for(int j=0; j<g[u].size(); j++)
{
ii v = g[u][j];
if(df[u] + v.second < df[v.first])
{
df[v.first] = df[u] + v.second;
pqf.push(ii(df[v.first],v.first));
}
}
//updating the result
if(res > df[u]+db[u])
res = df[u]+db[u];
//inserting the node in the list of processed nodes
if(p.insert(u).second == false)
break;
//dijkstra on reverse graph
ii fb = pqb.top(); pqb.pop();
d = fb.first;u = fb.second;
for(int j=0; j<gr[u].size(); j++)
{
ii v = gr[u][j];
if(db[u] + v.second < db[v.first])
{
db[v.first] = db[u] + v.second;
pqb.push(ii(db[v.first],v.first));
}
}
//updating the result
if(res > df[u]+db[u])
res = df[u]+db[u];
//inserting the nodes in the list of processed nondes
if(p.insert(u).second == false)
break;
if(pqf.empty() || pqb.empty())
break;
}
return;
}
int main(void)
{
int x,y,wt;
cin >> V >> E;
g.assign(V, vii());
gr.assign(V, vii());
df.assign(V,INF);
db.assign(V,INF);
for(int i=0; i<E; i++)
{
cin >> x >> y >> wt;
x--;y--;
g[x].push_back(ii(y,wt));
gr[y].push_back(ii(x,wt));
}
int s,t,q;
cin >> q;
while(q--)
{
res = INT_MAX;
cin >> s >> t;
s--; t--;
dijkstra(s,t);
if(res == INF)
cout << "-1\n";
else
cout << res << "\n";
fill(df.begin(),df.end(),INF);
fill(db.begin(),db.end(),INF);
}
return 0;
}