#include <bits/stdc++.h>
#define respagold ios_base::sync_with_stdio(0), cin.tie(0);
//#define int long long
#define ll long long
#define int2 __int128_t
#define FOR( i, x, n, d ) for( int i = x; i <= n; i += d )
#define FORR( i, x, n, d ) for( int i = x; i >= n; i -= d )
#define F first
#define S second
#define all(x) x.begin(), x.end()
#define sz(x) (int)(x.size())
#define pb push_back
#define ins insert
#define lb lower_bound
#define ub upper_bound
#define pii pair <int, int>
#define mkp make_pair
using namespace std;
const int N = 5e5 + 123;
const int inf = 1e9;
const int mod = 1e9 + 7;
int a[N], b[N], c[N], d[N], n, m, q, k, z, w, x, y, s[N], t[N], L[N], R[N], ans[N], p[N], siz[N];
vector <pii> g[N], vec;
vector <int> ord;
mt19937 rng( chrono::steady_clock::now().time_since_epoch().count());
int rand( int l, int r )
{
uniform_int_distribution <int> uid( l, r );
return uid( rng );
}
bool cmp( int a, int b )
{
return d[a] > d[b];
}
int par( int x )
{
if( x == p[x] ) return x;
return p[x] = par( p[x] );
}
void unite( int v, int u )
{
v = par(v), u = par(u);
if( v == u ) return;
if( siz[v] < siz[u] ) swap(v, u);
siz[v] += siz[u], p[u] = v;
}
void solve()
{
cin >> n >> m;
FOR( i, 1, n, 1 ) d[i] = inf, ord.pb(i);
FOR( i, 1, m, 1 )
{
cin >> a[i] >> b[i] >> c[i];
g[a[i]].pb({ b[i], c[i] });
g[b[i]].pb({ a[i], c[i] });
}
cin >> k;
set <pii> st;
FOR( i, 1, k, 1 ) cin >> x, st.ins({ 0, x }), d[x] = 0;
while( !st.empty() )
{
pii v = *st.begin();
st.erase( st.begin() );
for( auto to : g[v.S] )
{
if( d[to.F] > v.F + to.S )
{
st.erase({ d[to.F], to.F });
d[to.F] = v.F + to.S;
st.ins({ d[to.F], to.F });
}
}
}
sort( all( ord ), cmp );
cin >> q;
FOR( i, 1, q, 1 ) cin >> s[i] >> t[i], L[i] = 0, R[i] = 1e9, ans[i] = 0;
while( 1 )
{
vec.clear();
FOR( i, 1, n, 1 ) siz[i] = 1, p[i] = i;
FOR( i, 1, q, 1 )
{
if( L[i] <= R[i] ) vec.pb({ L[i] + R[i] >> 1, i });
}
if( !sz(vec) ) break;
sort( all( vec ) );
reverse( all( vec ) );
int lst = -1;
for( auto pp : vec )
{
int mn = pp.F, id = pp.S;
while( lst + 1 < sz(ord) && d[ord[lst + 1]] >= mn )
{
lst ++;
for( auto to : g[ord[lst]] ) if( d[to.F] >= mn ) unite( ord[lst], to.F );
}
if( par(s[id]) == par(t[id]) ) ans[id] = mn, L[id] = mn + 1;
else R[id] = mn - 1;
}
}
FOR( i, 1, q, 1 ) cout << ans[i] << '\n';
}
signed main()
{
// freopen("connect.in", "r", stdin);
// freopen("connect.out", "w", stdout);
respagold
int test = 1;
if( !test ) cin >> test;
while( test -- )
{
solve();
}
}
// solved by KluydQ
/*
9 12
1 9 4
1 2 5
2 3 7
2 4 3
4 3 6
3 6 4
8 7 10
6 7 5
5 8 1
9 5 7
5 4 12
6 8 2
2
4 7
5
1 6
5 3
4 8
5 8
1 5
*/
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |