제출 #982375

#제출 시각아이디문제언어결과실행 시간메모리
982375Godgift42경주 (Race) (IOI11_race)C++17
43 / 100
3011 ms43648 KiB
#include <bits/stdc++.h>
using namespace std;


vector<vector<pair<int,int>>> adj;
int n, k;
vector<int> subtr;
vector<bool> vis;
unordered_map<int,int> mp;
int ans=INT_MAX;

void findsize(int u, int p){
    subtr[u]=1;
    for(auto [v,w]:adj[u]){
        if(v!=p and !vis[v]){
            findsize(v,u);
            subtr[u]+=subtr[v];
        }
    }
}

int findcentroid(int u, int p, int sz){
    for(auto [v,w]:adj[u]){
        if(v!=p and !vis[v] and subtr[v]>sz/2)return findcentroid(v,u,sz);
    }
    return u;
}

void dfs1(int u, int p, int dist, int depth){
    if(dist>k)return;
    if(mp[k-dist] or k==dist) ans=min(ans,mp[k-dist]+depth);
    for(auto [v,w]:adj[u]){
        if(v!=p and !vis[v]){
            dfs1(v,u,dist+w,depth+1);
        }
    }
}

void dfs2(int u, int p, int dist, int depth){
    if(dist>k)return;
    if(mp[dist]==0)mp[dist]=depth;
    else mp[dist]=min(mp[dist],depth);
    for(auto [v,w]:adj[u]){
        if(v!=p and !vis[v]){
            dfs2(v,u,dist+w,depth+1);
        }
    }
}

void buildcentroid(int u, int p){
    findsize(u,u);
    int c=findcentroid(u,u,subtr[u]);
    vis[c]=true;
    for(auto [v,w]:adj[c]){
        if(v!=p and !vis[v]){
            dfs1(v,c,w,1);
            dfs2(v,c,w,1);
        }
    }
    mp.clear();
    for(auto [v,w]:adj[c]){
        if(!vis[v])buildcentroid(v,c);
    }
}

int best_path(int N, int K, int H[][2], int L[]){
    n=N;
    k=K;
    adj.resize(n);
    subtr.resize(n);
    vis.resize(n);
    for(int i=0;i<n-1;i++){
        adj[H[i][1]].push_back({H[i][0],L[i]});
        adj[H[i][0]].push_back({H[i][1],L[i]});
    }
    buildcentroid(0,-1);
    if(ans==INT_MAX)return -1;
    return ans;
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...