# | 제출 시각 | 아이디 | 문제 | 언어 | 결과 | 실행 시간 | 메모리 |
---|---|---|---|---|---|---|---|
937570 | ByeWorld | 공장들 (JOI14_factories) | C++14 | 0 ms | 0 KiB |
이 제출은 이전 버전의 oj.uz에서 채점하였습니다. 현재는 제출 당시와는 다른 서버에서 채점을 하기 때문에, 다시 제출하면 결과가 달라질 수도 있습니다.
#include <bits/stdc++.h>
#define fi first
#define se second
#define pb push_back
#define int long long
#define lf (id<<1)
#define rg ((id<<1)|1)
#define md ((l+r)>>1)
#define ld long double
using namespace std;
typedef pair<int,int> pii;
typedef pair<string, pii> ipii;
const int INF = 1e18+10;
const int MAXN = 5e5+10;
const int MAXK = 1010;
const int LOG = 20;
int n, q;
vector <pii> adj[MAXN];
int dep[MAXN], up[MAXN], anc[MAXN][LOG+5];
int x[MAXN], y[MAXN];
void dfs(int nw, int par){
anc[nw][0] = par;
for(auto nx : adj[nw]){
if(nx.fi == par) continue;
up[nx.fi] = up[nw]+nx.se;
dep[nx.fi] = dep[nw]+1;
dfs(nx.fi, nw);
}
}
int LCA(int x, int y){
if(dep[x] > dep[y]) swap(x, y); //gerakin y
for(int i=LOG-1; i>=0; i--){
if(dep[anc[y][i]] >= dep[x]) y = anc[y][i]; // dibawah ato sama dengan
}
if(x == y) return x;
for(int i=LOG-1; i>=0; i--){
if(anc[y][i] != anc[x][i]){
x = anc[x][i];
y = anc[y][i];
}
}
return anc[x][0];
}
int DIST(int x, int y){
int lca = LCA(x, y);
return up[x]+up[y]-2*up[lca];
}
signed main(){
ios_base::sync_with_stdio(0);cin.tie(0);cout.tie(0);
cin >> n >> q;
for(int i=1; i<=n-1; i++){
int x, y, z; cin >> x >> y >> z;
x++; y++;
adj[x].pb({y, z}); adj[y].pb({x, z});
}
dfs(1, -1);
for(int i=1; i<LOG; i++){
for(int j=1; j<=n; j++){
anc[j][i] = anc[anc[j][i-1]][i-1];
}
}
while(q--){
int s, t; cin >> s >> t;
for(int i=1; i<=s; i++){ cin >> x[i]; x[i]++; }
for(int i=1; i<=t; i++){ cin >> y[i]; y[i]++; }
int mn = INF;
for(int i=1; i<=s; i++){
for(int j=1; j<=t; j++){
mn = min(mn, DIST(x[i], y[j]));
}
}
cout << mn << '\n';
}
//cout << LCA(4, 3) << " p\n";
}