[模板]Prufer序列

过程详解

code

#include <bits/stdc++.h>

using namespace std;

typedef long long ll;
const int maxn = 5e6 + 3;

int n, m, du[maxn];
ll ans, p[maxn], fa[maxn];

inline int read()
{
    int x = 0, f = 1;
    char ch = getchar();
    while(ch < '0' || ch > '9')
    {
        if(ch == '-')
        {
            f = -1;
        }
        ch = getchar();
    }
    while(ch >= '0' && ch <= '9')
    {
        x = (x << 1) + (x << 3) + (ch^48);
        ch = getchar();
    }
    return x * f;
}

void Tree_to_Prufer()
{
    for(int i=1; i<=n-1; i++) fa[i] = read(), du[fa[i]]++;
    for(int i=1,now=1; i<=n-1; i++,now++)
    {
        while(du[now]) now++;
        p[i] = fa[now];
        while(i<n-2 && !--du[p[i]] && p[i]<now) p[i+1] = fa[p[i]], i++;
    }
    for(int i=1; i<=n-2; i++) ans ^= i*p[i];
}

void Prufer_to_Tree()
{
    for(int i=1; i<=n-2; i++) p[i] = read(), du[p[i]]++;
    p[n-1] = n;
    for(int i=1,now=1; i<=n-1; i++,now++)
    {
        while(du[now]) now++;
        fa[now] = p[i];
        while(i<n-1 && !--du[p[i]] && p[i]<now) fa[p[i]] = p[i+1], i++;
    }
    for(int i=1; i<=n-1; i++) ans ^= i*fa[i];
}

int main()
{
    n = read(); m = read();
    if(m == 1) Tree_to_Prufer();
    else Prufer_to_Tree();
    printf("%lld\n", ans);

    return 0;
}
posted @ 2022-10-10 19:51  Catherine_leah  阅读(17)  评论(0)    收藏  举报
/* */