[模板]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;
}
时光花火,水月星辰

浙公网安备 33010602011771号