Submission #331836

# Submission time Handle Problem Language Result Execution time Memory
331836 2020-11-30T11:35:48 Z EndRay Mergers (JOI19_mergers) C++17
0 / 100
84 ms 26468 KB
#include<bits/stdc++.h>

using namespace std;

const int N = 5e5+1, logN = 19+1;

int n, k;
vector<int> g[N];
int s[N];
int p[logN][N], h[N];

void dfs_init(int v=0, int pr=-1){
    for(int u : g[v]) if(u != pr){
        p[0][u] = v;
        h[u] = h[v]+1;
        dfs_init(u, v);
    }
}

void init(){
    p[0][0] = 0;
    h[0] = 0;
    dfs_init();
    for(int d = 1; d < logN; ++d)
        for(int i = 0; i < n; ++i)
            p[d][i] = p[d-1][p[d-1][i]];
}

int lca(int u, int v){
    if(h[u] < h[v])
        swap(u, v);
    int d = h[u] - h[v];
    for(int i = 0; i < logN; ++i)
        if((d&(1<<i)))
            u = p[i][u];
    for(int i = logN-1; i >= 0; --i)
        if(p[i][u] != p[i][v]){
            u = p[i][u];
            v = p[i][v];
        }
    return (u == v ? u : p[0][u]);
}

int color_lca[N];
int ans = 0;

int dfs(int v=0, int pr=-1){
    int w = color_lca[s[v]];
    bool ok = (g[v].size() == 1);
    for(int u : g[v]) if(u != pr){
        int l = dfs(u, v);
        if(l == -1)
            continue;
        ok = true;
        w = lca(l, w);
    }
    if(!ok)
        return -1;
    if(v == w){
        ++ans;
        return -1;
    }
    return w;
}

int main(){
    ios_base::sync_with_stdio(false);
    cout.tie(0);
    cin.tie(0);
    cin >> n >> k;
    for(int i = 0; i < n-1; ++i){
        int u, v;
        cin >> u >> v;
        --u; --v;
        g[u].push_back(v);
        g[v].push_back(u);
    }
    for(int i = 0; i < n; ++i){
        cin >> s[i];
        --s[i];
    }
    init();
    for(int i = 0; i < k; ++i)
        color_lca[i] = -1;
    for(int i = 0; i < n; ++i){
        if(color_lca[s[i]] == -1)
            color_lca[s[i]] = i;
        color_lca[s[i]] = lca(i, color_lca[s[i]]);
    }
    dfs(0);
    cout << (ans == 1 ? 0 : ((ans+1)/2)) << "\n";
}
# Verdict Execution time Memory Grader output
1 Incorrect 8 ms 12416 KB Output isn't correct
2 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Incorrect 8 ms 12416 KB Output isn't correct
2 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Incorrect 8 ms 12416 KB Output isn't correct
2 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Correct 84 ms 25828 KB Output is correct
2 Correct 84 ms 26468 KB Output is correct
3 Incorrect 13 ms 12780 KB Output isn't correct
4 Halted 0 ms 0 KB -
# Verdict Execution time Memory Grader output
1 Incorrect 8 ms 12416 KB Output isn't correct
2 Halted 0 ms 0 KB -