题解:P17855 [LBA-OI R6 C] 哥德巴赫猜想
题目链接
更差的阅读体验
本题解中的所有
思路
考虑把
操作 1 相当于加入一段路径,操作 2 相当于取出权值最大的路径,把权值作为答案,并把这条路径上最大的
还剩下一个问题:如何在总空间复杂度
先树剖,每个节点预处理它到它所在重链的链顶的路径上
时间复杂度
代码
赛时代码,比较丑陋,用 C++98 开 O2 能过。
#include <bits/stdc++.h>
using namespace std;
#define pii pair<int,int>
#define ll long long
const int N=1e6+5,P=1e9+7;
char *p1,*p2,buf[100000];
#define nc() (p1==p2 && (p2=(p1=buf)+fread(buf,1,100000,stdin),p1==p2)?EOF:*p1++)
int rd()
{
int x=0,f=1;
char ch=nc();
while(ch<48||ch>57)
{
if(ch=='-')
f=-1;
ch=nc();
}
while(ch>=48&&ch<=57)
x=x*10+ch-48,ch=nc();
return x*f;
}
int n,m,a[N],fa[N],rt[N],top[N],sz[N],ch[N],mx[N],dfn[N],tot,b[N];
int hd[N],nxt[N],to[N],k;
struct triple
{
int x,y,z;
};
vector<triple> p;
priority_queue<pii> q;
void link(int x,int y)
{
nxt[++k]=hd[x];
hd[x]=k;
to[k]=y;
}
namespace sgt
{
int mx[N*4];
void pushup(int x)
{
if(a[mx[x*2]]>a[mx[x*2+1]])
mx[x]=mx[x*2];
else
mx[x]=mx[x*2+1];
}
void build(int x=1,int l=1,int r=n)
{
if(l==r)
{
mx[x]=b[l];
return;
}
int mid=(l+r)>>1;
build(x*2,l,mid);
build(x*2+1,mid+1,r);
pushup(x);
}
int getmax(int pl,int pr,int x=1,int l=1,int r=n)
{
if(l>=pl&&r<=pr)
return mx[x];
int mid=(l+r)>>1;
if(mid>=pr)
return getmax(pl,pr,x*2,l,mid);
if(mid<pl)
return getmax(pl,pr,x*2+1,mid+1,r);
int u=getmax(pl,pr,x*2,l,mid),v=getmax(pl,pr,x*2+1,mid+1,r);
if(a[u]>a[v])
return u;
return v;
}
}
void dfs1(int x)
{
sz[x]=1;
for(int i=hd[x];i;i=nxt[i])
{
int y=to[i];
rt[y]=rt[x];
dfs1(y);
sz[x]+=sz[y];
if(sz[y]>sz[ch[x]])
ch[x]=y;
}
}
void dfs2(int x)
{
dfn[x]=++tot;
b[tot]=x;
if(!ch[x])
return;
top[ch[x]]=top[x];
mx[ch[x]]=ch[x];
if(a[mx[x]]>a[ch[x]])
mx[ch[x]]=mx[x];
dfs2(ch[x]);
for(int i=hd[x];i;i=nxt[i])
{
int y=to[i];
if(y!=ch[x])
{
top[y]=y;
mx[y]=y;
dfs2(y);
}
}
}
int getval(int x,int y)
{
int z=0;
while(top[x]!=top[y])
{
if(a[mx[x]]>a[z])
z=mx[x];
x=fa[top[x]];
}
int w=sgt::getmax(dfn[y],dfn[x]);
if(a[w]>a[z])
return w;
return z;
}
int jump(int x,int y)
{
int lst=0;
while(top[x]!=top[y])
lst=x,x=fa[top[x]];
if(x==y)
return top[lst];
return ch[y];
}
void add(int x,int y)
{
int z=getval(x,y);
p.push_back({x,y,z});
q.push({a[z],p.size()-1});
}
void del(int id)
{
int x=p[id].x,y=p[id].y,z=p[id].z;
if(z!=y)
add(fa[z],y);
if(z!=x)
add(x,jump(x,z));
}
signed main()
{
scanf("%d%d",&n,&m);
for(int i=1;i<=n;i++)
{
fa[i]=rd();
if(fa[i])
link(fa[i],i);
}
for(int i=1;i<=n;i++)
a[i]=rd();
for(int i=1;i<=n;i++)
if(!fa[i])
rt[i]=top[i]=i,dfs1(i),dfs2(i);
sgt::build();
ll ans=0,tot=0;
while(m--)
{
int op,x;
op=rd();
if(op==1)
{
x=rd();
add(x,rt[x]);
}
else
{
tot++;
if(!q.size())
continue;
pii now=q.top();
q.pop();
ans^=1ll*tot*now.first;
del(now.second);
}
}
printf("%lld",ans);
return 0;
}