Submission #1256824

#TimeUsernameProblemLanguageResultExecution timeMemory
1256824tvgkMergers (JOI19_mergers)C++20
0 / 100
62 ms41408 KiB
#include<bits/stdc++.h>
using namespace std;
#define task "a"
#define se second
#define fi first
#define ll long long
#define ii pair<ll, ll>
const long mxN = 5e5 + 7;

int par[mxN][25], n, h[mxN], dp[mxN], m, dsu[mxN], cnt[mxN];
bool vis[mxN];
vector<int> vc[mxN], w[mxN];

void Build(int j)
{
    for (int i = 1; i <= 19; i++)
        par[j][i] = par[par[j][i - 1]][i - 1];

    for (int i : w[j])
    {
        if (h[i])
            continue;

        h[i] = h[j] + 1;
        par[i][0] = j;
        Build(i);
    }
}

int LCA(int u, int v)
{
    if (h[u] < h[v])
        swap(u, v);

    for (int i = 20; i >= 0; i--)
    {
        if (h[par[u][i]] >= h[v])
            u = par[u][i];
    }

    if (u == v)
        return u;

    for (int i = 20; i >= 0; i--)
    {
        if (par[u][i] != par[v][i])
        {
            u = par[u][i];
            v = par[v][i];
        }
    }
    return par[u][0];
}

int Find(int j)
{
    if (dsu[j] == j)
        return j;
    else
        return dsu[j] = Find(dsu[j]);
}

void Union(int u, int v)
{
    u = Find(u);
    v = Find(v);

    dsu[u] = v;
}

int main()
{
    ios_base::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    //freopen(task".INP", "r", stdin);
    //freopen(task".OUT", "w", stdout);

    cin >> n >> m;
    for (int i = 1; i < n; i++)
    {
        int u, v;
        cin >> u >> v;
        w[u].push_back(v);
        w[v].push_back(u);
    }
    h[1] = 1;
    Build(1);

    for (int i = 1; i <= n; i++)
    {
        int tmp;
        cin >> tmp;
        vc[tmp].push_back(i);
        dsu[i] = i;
    }

    Union(1, 0);
    for (int i = 1; i <= m; i++)
    {
        int root = vc[i][0];
        for (int j : vc[i])
            root = LCA(root, j);

        for (int j : vc[i])
        {
            while (1)
            {
                j = Find(j);
                if (h[j] <= h[root])
                    break;

                Union(j, par[j][0]);
            }
        }
    }

    for (int i = 1; i <= n; i++)
    {
        for (int j : w[i])
        {
            if (Find(i) != Find(j))
                cnt[Find(i)]++;
        }
    }

    int ans = 0;
    for (int i = 1; i <= n; i++)
        ans += (cnt[i] == 1);
    cout << (ans + 1) / 2;
}

#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...
#Verdict Execution timeMemoryGrader output
Fetching results...