제출 #1356488

#제출 시각아이디문제언어결과실행 시간메모리
1356488islam_2010Roadside Advertisements (NOI17_roadsideadverts)C++20
0 / 100
8 ms4180 KiB

#include <bits/stdc++.h>
using namespace std;
 
#define int long long
 
const int sz = 5e4 + 5;

int n;
vector<pair<int, int>> g[sz];
int depth[sz];
int dist[sz];
int tin[sz];
int t;
int up[sz][19];

void dfs(int node, int p){
    up[node][0] = p;
    for(int i = 1; i < 18; i++){
        up[node][i] = up[up[node][i-1]][i-1];
    }tin[node] = ++t;
    for(auto i: g[node]){
        if(i.first != p){
            depth[i.first] = depth[node] + 1;
            dist[i.first] = dist[node] + i.second;
            dfs(i.first, node);
        }
    }
}

int lift(int node, int k){
    for(int i = 0; i < 17; i++){
        if(k&(1<<i)){
            node = up[node][i];
        }
    }return node;
}

int LCA(int a, int b){
    if(depth[a] < depth[b]) swap(a, b);
    a = lift(a, depth[a] - depth[b]);
    if(a == b) return a;
    for(int i = 17; i >= 0; i--){
        if(up[a][i] != up[b][i]){
            a = up[a][i];
            b = up[b][i];
        }
    }return up[a][0];

}





signed main(){
    ios_base::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> n;
    for(int i = 0; i < n-1; i++){
        int u, v, w;
        cin >> u >> v >> w;
        g[u].push_back({v, w});
        g[v].push_back({u, w});
    }dfs(0, -1);
    int m;
    cin >> m;
    while(m--){
        vector<int> a;
        for(int i = 0; i < 5; i++){
            int b;
            cin >> b;
            a.push_back(b);
        }
        sort(a.begin(), a.end(), [&](int x, int y){
            return tin[x] < tin[y];
        });
        int ans = 0;
        for(int i = 0; i < 5; i++){
            int x = LCA(a[i], a[(i+1)%5]);
            ans += dist[a[i]] + dist[a[(i+1)%5]] - 2*dist[x];
        }cout << ans/2 << endl;

    }
    

    return 0;
}
#결과 실행 시간메모리채점기 출력
결과를 불러오는 중입니다…
#결과 실행 시간메모리채점기 출력
결과를 불러오는 중입니다…
#결과 실행 시간메모리채점기 출력
결과를 불러오는 중입니다…
#결과 실행 시간메모리채점기 출력
결과를 불러오는 중입니다…