제출 #1271465

#제출 시각아이디문제언어결과실행 시간메모리
1271465danilofv경주 (Race) (IOI11_race)C++20
21 / 100
3096 ms39640 KiB
#include <bits/stdc++.h>
using namespace std;

vector<vector<pair<int, int>>> grafo;
void dfs2(int src, int parent, int currPathTam, int currPathArestas);
vector<int> subtrees;
vector<bool> visited;
int minCam = INT_MAX;
unordered_map<int, int> melhor;

void calc_subtrees(int src, int parent){
    subtrees[src] = 1;
    for (auto& vz: grafo[src]){
        int v = vz.first;
        if (v == parent || visited[v]) continue; 
        calc_subtrees(v, src);
        subtrees[src] += subtrees[v];
    }
}

int centroid(int src, int parent, int subTreeSize){
    for (auto vz: grafo[src]){
        int v = vz.first;
        if (v == parent || visited[v]) continue; 
        if (subtrees[v] > subTreeSize/2){
            return centroid(v, src, subTreeSize);
        }
    }
    return src;
}

int find_centroid(int beg, int parent){
    // subtrees.assign(grafo.size(), 0);        
    calc_subtrees(beg, parent);
    return centroid(beg, -1, subtrees[beg]);
}

void dfs1(int src, int parent, int currPathTam, int currPathArestas, int K){
    if (visited[src]) return; 
    if (melhor.find(K - currPathTam) != melhor.end())
        minCam = min(minCam, currPathArestas + melhor[K - currPathTam]);

    for (int i = 0; i< (int)grafo[src].size() ; i++){
        auto &[vz, w] =  grafo[src][i];
        if (parent == vz || visited[vz]) continue; 
        dfs1(vz, src, currPathTam + w, currPathArestas + 1, K);
    }
}

void dfs2(int src, int parent, int currPathTam, int currPathArestas){
    if (visited[src]) return;
    if (melhor.find(currPathTam)!= melhor.end())
        melhor[currPathTam ] = min(melhor[currPathTam], currPathArestas);
    else
        melhor[currPathTam] = currPathArestas;

    for (auto &[vz, w]: grafo[src]){
        if (vz == parent || visited[vz]) continue;
        dfs2(vz, src, currPathTam + w, currPathArestas + 1);
    }
}

void solve(int start, int K){
    int cntd = find_centroid(start, -1);

    visited[cntd] = true;

    melhor.clear();
    melhor[0] = 0;
    for (auto &[v, w] : grafo[cntd]){
        if (visited[v]) continue;
        dfs1(v, cntd, w, 1, K);
        dfs2(v, cntd, w, 1);
    }

    for (auto &[v, w] : grafo[cntd]){
        if (!visited[v]){
            solve(v, K);
        }
    }
}


int best_path(int N, int K, int H[][2], int L[])
{
    minCam = INT_MAX;
    visited.assign(N, false);
    subtrees.assign(N, 0);
    grafo.resize(N);
    for (int i = 0; i < N - 1; i++)
    {
        grafo[H[i][0]].push_back({H[i][1], L[i]});
        grafo[H[i][1]].push_back({H[i][0], L[i]});
    }

    solve(0,K);

    return (minCam == INT_MAX ? -1 : minCam);
}
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...