This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
//#pragma GCC optimize("Ofast")
#define fi first
#define se second
#define ll long long
using namespace std;
const int N = 1e5 + 7;
const int mod = 1e9 + 7;
int n,m,q,k;
int l = 1;
int cnt;
int a[N];
int d[N];
int p[N];
int tin[N];
int dep[N];
int tout[N];
bool used[N];
vector < int > g[N];
vector < vector < int > > up;
vector < pair < int , int > > v[N];
int get( int x )
{
return (x == p[x] ? x : p[x] = get(p[x]));
}
void dfs( int x , int p )
{
tin[x] = ++cnt;
up[x][0] = p;
for( int i = 1; i <= l; i++ ){
up[x][i] = up[up[x][i - 1]][i - 1];
}
for( auto y : g[x] ){
if( y != p ){
dep[y] = dep[x] + 1;
dfs(y , x);
}
}
tout[x] = cnt;
}
bool upper( int x , int y )
{
return (tin[x] <= tin[y] && tout[x] >= tout[y]);
}
int lca( int x , int y )
{
if( upper(x , y) )return x;
if( upper(y , x) )return y;
for( int i = l; i >= 0; i-- ){
if( !upper(up[x][i] , y) ){
x = up[x][i];
}
}
return up[x][0];
}
void solve()
{
cin >> n >> m;
while( (1 << l) <= n )l++;
up.resize(n + 10);
for( int i = 0; i <= n; i++ ){
up[i].resize(l + 10);
p[i] = i;
d[i] = 1e9;
}
for( int i = 1; i <= m; i++ ){
int x,y,z;
cin >> x >> y >> z;
v[x].push_back({y , z});
v[y].push_back({x , z});
}
set < pair < int , int > > s;
cin >> k;
for( int i = 1; i <= k; i++ ){
int x;
cin >> x;
d[x] = 0;
s.insert({0 , x});
}
while( !s.empty() ){
auto x = s.begin()->se;
s.erase(s.begin());
for( auto y : v[x] ){
if( d[x] + y.se < d[y.fi] ){
s.erase({d[y.fi] , y.fi});
d[y.fi] = d[x] + y.se;
s.insert({d[y.fi] , y.fi});
}
}
}
vector < pair < int , int > > vv;
for( int i = 1; i <= n; i++ ){
vv.push_back({d[i] , i});
}
int start = 0;
sort( vv.rbegin() , vv.rend() );
for( auto y : vv ){
used[y.se] = true;
for( auto z : v[y.se] ){
int xx = get(z.fi);
int yy = y.se;
if( used[z.fi] && xx != yy ){
p[xx] = yy;
g[yy].push_back(xx);
g[xx].push_back(yy);
}
}
}
dfs(vv[n - 1].se , vv[n - 1].se);
cin >> q;
for( int i = 1; i <= q; i++ ){
int x,y;
cin >> x >> y;
int c = lca(x , y);
cout << d[c] << "\n";
}
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0); cout.tie(0);
//freopen( "input.txt" , "r" , stdin );
//freopen( "output.txt" , "w" , stdout );
int t = 1;//cin >> t;
while( t-- ){
solve();
}
}
Compilation message (stderr)
plan.cpp: In function 'void solve()':
plan.cpp:105:9: warning: unused variable 'start' [-Wunused-variable]
int start = 0;
^~~~~
# | 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... |