이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include<bits/stdc++.h>
using namespace std;
#define jizz ios_base::sync_with_stdio(false);cin.tie(NULL);
typedef long long ll;
typedef pair<int,int> pii;
#define F first
#define S second
#define FOR(i,n) for(int i=0;i<n;i++)
#define FOO(i,a,b) for(int i=a;i<=b;i++)
#define OOF(i,a,b) for(int i=a;i>=b;i--)
#define ALL(x) (x).begin(),(x).end()
#define pb push_back
#define mkp make_pair
const int MAXN=1E5+10, INF=2E9;
struct edge{
int a, b, w;
edge(int a, int b, int w):a(a),b(b),w(w){};
};
struct DSU{
int data[MAXN];
void init(int sz){
FOO(i,1,sz) data[i]=i;
}
int anc(int x){
if(x==data[x]) return x;
return data[x]=anc(data[x]);
}
void onion(int a, int b){
int x=anc(a), y=anc(b);
data[y]=x;
}
} dsu;
vector<pii> G[MAXN], T[MAXN];
vector<edge> edges;
int n, m, k, q, dis[MAXN], anc[18][MAXN], mv[18][MAXN], dep[MAXN];
priority_queue<pii, vector<pii>, greater<pii> > pq;
void Dijkstra(){
pii cur;
while(!pq.empty()){
do{
cur=pq.top();
pq.pop();
} while(!pq.empty()&&cur.F>dis[cur.S]);
for(auto i:G[cur.S]){
if(dis[cur.S]+i.S<dis[i.F]){
dis[i.F]=dis[cur.S]+i.S;
pq.push(mkp(dis[i.F],i.F));
}
}
}
}
void MST(){
dsu.init(n);
for(auto i:edges){
if(dsu.anc(i.a)!=dsu.anc(i.b)){
T[i.a].pb(mkp(i.b,i.w));
T[i.b].pb(mkp(i.a,i.w));
dsu.onion(i.a,i.b);
}
}
}
void dfs(int x, int f, int c){
anc[0][x]=f;
mv[0][x]=c;
dep[x]=dep[f]+1;
for(auto i:T[x]){
if(i.F==f) continue;
dfs(i.F,x,i.S);
}
}
int Query(int x, int y){
if(dep[x]<dep[y]) swap(x,y);
int res=INF;
int b=dep[x]-dep[y];
for(int c=0;b>0;c++){
if(b%2){
res=min(res,mv[c][x]);
x=anc[c][x];
}
b/=2;
}
if(x==y) return res;
for(int j=__lg(n)+1;j>=0;j--){
if(anc[j][x]!=anc[j][y]){
res=min(res,min(mv[j][x],mv[j][y]));
x=anc[j][x];
y=anc[j][y];
}
}
return min(res,min(mv[0][x],mv[0][y]));
}
int main(){ jizz
cin>>n>>m;
FOR(i,m){
int a, b, w;
cin>>a>>b>>w;
G[a].pb(mkp(b,w));
G[b].pb(mkp(a,w));
}
cin>>k;
FOR(i,k){
int g;
cin>>g;
G[0].pb(mkp(g,0));
}
FOO(i,1,n) dis[i]=INF;
dis[0]=0;
pq.push(mkp(0,0));
Dijkstra();
FOO(x,1,n){
for(auto i:G[x]){
if(x<i.F) edges.pb(edge(x,i.F,min(dis[x],dis[i.F])));
}
}
sort(ALL(edges),[](edge x, edge y){return x.w>y.w;});
MST();
dfs(1,0,INF);
for(int i=1;(1<<i)<=n;i++){
for(int j=1;j<=n;j++){
anc[i][j]=anc[i-1][anc[i-1][j]];
mv[i][j]=min(mv[i-1][j],mv[i-1][anc[i-1][j]]);
}
}
cin>>q;
FOR(i,q){
int s, t;
cin>>s>>t;
cout<<Query(s,t)<<"\n";
}
return 0;
}
/*
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... |