-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbidirectional-dijkstra.cpp
More file actions
153 lines (139 loc) · 2.51 KB
/
Copy pathbidirectional-dijkstra.cpp
File metadata and controls
153 lines (139 loc) · 2.51 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
147
148
149
150
151
152
#include<bits/stdc++.h>
using namespace std;
typedef unsigned long long int ull;
typedef long long int ll;
typedef long double ld;
typedef pair<ll, ll> pi;
#define sc(n) scanf("%lld",&n)
#define scc(n,m) scanf("%lld %lld",&n,&m)
#define sccc(x,y,z) scanf("%lld %lld %lld",&x,&y,&z)
#define pf(n) printf("%lld\n",n)
#define pff(n,m) printf("%lld %lld\n",n,m)
#define pfn printf("\n")
#define pb push_back
#define fi first
#define se second
#define mem(n,m) memset(n,m,sizeof(n))
vector<ll> mp[1000005];
vector<ll> mpr[1000005];
unordered_map<ll,unordered_map<ll,ll>> wt{};
unordered_map<ll,unordered_map<ll,ll>> wtr{};
ll dist[1000005];
ll distr[1000005];
bool visit[1000005];
bool visitr[1000005];
priority_queue<pi, vector<pi>, greater<pi> > pq;
priority_queue<pi, vector<pi>, greater<pi> > pqr;
int main()
{
ll n{},m{},x{},y{},l{},q{};
scc(n,m);
for(ll i=0;i<m;i++)
{
sccc(x,y,l);
mp[x].push_back(y);
mpr[y].push_back(x);
wt[x][y]=l;
wtr[y][x]=l;
}
sc(q);
while(q--)
{
while(!pq.empty())
{
pq.pop();
}
while(!pqr.empty())
{
pqr.pop();
}
scc(x,y);
for(ll i=1;i<=n;i++)
{
visit[i]=false;
visitr[i]=false;
dist[i]=LLONG_MAX;
distr[i]=LLONG_MAX;
}
dist[x]=0;
distr[y]=0;
set<ll> proc{};
set<ll> procr{};
bool flag=true;
for(ll i=1;i<=n;i++)
{
pq.push({dist[i],i});
pqr.push({distr[i],i});
}
while(!pq.empty() && !pqr.empty())
{
ll p=pq.top().se;
pq.pop();
if(!visit[p])
{
visit[p]=true;
for(auto w:mp[p])
{
if(dist[p]!=LLONG_MAX)
if(dist[w]>dist[p]+wt[p][w])
{
dist[w]=dist[p]+wt[p][w];
pq.push({dist[w],w});
}
}
proc.insert(p);
if(procr.find(p)!=procr.end())
{
flag=false;
break;
}
}
p=pqr.top().se;
pqr.pop();
if(!visitr[p])
{
visitr[p]=true;
for(auto w:mpr[p])
{
if(distr[p]!=LLONG_MAX)
if(distr[w]>distr[p]+wtr[p][w])
{
distr[w]=distr[p]+wtr[p][w];
pqr.push({distr[w],w});
}
}
procr.insert(p);
if(proc.find(p)!=proc.end())
{
flag=false;
break;
}
}
}
if(!flag)
{
ll ans=LLONG_MAX;
for(auto u:proc)
{
if(dist[u]!=LLONG_MAX && distr[u]!=LLONG_MAX)
if(dist[u]+distr[u]<ans)
ans=dist[u]+distr[u];
}
for(auto u:procr)
{
if(dist[u]!=LLONG_MAX && distr[u]!=LLONG_MAX)
if(dist[u]+distr[u]<ans)
ans=dist[u]+distr[u];
}
if(ans==LLONG_MAX)
printf("-1\n");
else
pf(ans);
}
else
{
printf("-1\n");
}
}
return 0;
}