이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define F first
#define S second
const int N = 1e5+3;
vector<pair<int, pair<int, int>>> edges;
vector<pair<int, int>> adj[N], g[N];
int dist[N], mark[N], p[N], sz[N], tin[N], tout[N];
int up[N][17], cost[N][17];
int timer=-1;
int find(int v){
if(p[v]==v)return v;
return p[v]=find(p[v]);
}
void merge(int u, int v){
u=find(u);
v=find(v);
if(u==v)return;
if(sz[u]<sz[v])swap(u, v);
sz[u]+=sz[v];
p[v]=u;
}
void dfs(int v, int par){
tin[v]=++timer;
for(int i=1; i<17; i++){
up[v][i]=up[up[v][i-1]][i-1];
cost[v][i]=min(cost[v][i-1], cost[up[v][i-1]][i-1]);
}
for(auto to : adj[v]){
if(to.F!=par){
up[to.F][0]=v;
cost[to.F][0]=to.S;
dfs(to.F, v);
}
}
tout[v]=++timer;
}
bool isanc(int u, int v){
if(tin[u]<=tin[v] && tout[u]>=tout[v])return 1;
return 0;
}
int lca(int u, int v){
if(isanc(v, u))swap(u, v);
int mx=1e9;
if(!isanc(u, v)){
for(int i=16; i>=0; i--){
if(!isanc(up[u][i], v)){
mx=min(mx, cost[u][i]);
u=up[u][i];
}
}
mx=min(mx, cost[u][0]);
u=up[u][0];
}
for(int i=16; i>=0; i--){
if(!isanc(v, u)){
mx=min(mx, cost[v][i]);
v=up[v][i];
}
}
mx=min(mx, cost[v][0]);
return mx;
}
int main()
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int n, m;
cin >> n >> m;
for(int i=0; i< m; i++){
int a, b, c;
cin >> a >> b >> c;
g[a].pb({b, c});
g[b].pb({a, c});
edges.pb({c, {a, b}});
}
int k;
cin >> k;
priority_queue<pair<int, int>, vector<pair<int, int>>, greater<pair<int, int>>> pq;
for(int i=0; i<=n; i++)dist[i]=1e9;
for(int i=0; i< k; i++){
int a;
cin >> a;
pq.push({0, a});
dist[a]=0;
}
while(pq.size()){
auto pr = pq.top();
pq.pop();
int v = pr.S;
if(mark[v])continue;
mark[v]=1;
for(auto to : g[v]){
if(mark[to.F])continue;
if(to.S+pr.F < dist[to.F]){
dist[to.F]=to.S+pr.F;
pq.push({dist[to.F], to.F});
}
}
}
for(auto & e : edges){
e.F = min(dist[e.S.F], dist[e.S.S]);
}
sort(edges.begin(), edges.end());
reverse(edges.begin(), edges.end());
for(int i=1; i<=n; i++){
p[i]=i;
sz[i]=1;
}
for(auto e : edges){
if(find(e.S.F)!=find(e.S.S)){
merge(e.S.F, e.S.S);
adj[e.S.F].pb({e.S.S, e.F});
adj[e.S.S].pb({e.S.F, e.F});
}
}
up[1][0]=1;
cost[1][0]=1e9;
dfs(1, 0);
int q;
cin >> q;
while(q--){
int a, b;
cin >> a >> b;
cout << lca(a, b) << '\n';
}
}
# | 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... |