似乎正解是LCT。。这也是我学LCT做的第一道题。。然而今天写了一发分块看起来已经碾压LCT了。。。
两种都算模板级别的题了,分块更好写一些。
LCT:
#include<iostream>
#include<cstdio>
#define N 200005
using namespace std;
int n,m,next[N],tree[N][2],fa[N],size[N],s[N];
bool rev[N];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline bool isroot(int x)
{
return tree[fa[x]][0]!=x&&tree[fa[x]][1]!=x;
}
inline void pushup(int x)
{
size[x]=size[tree[x][0]]+size[tree[x][1]]+1;
}
inline void pushdown(int x)
{
if (rev[x])
{
rev[x]^=1; rev[tree[x][0]]^=1; rev[tree[x][1]]^=1;
swap(tree[x][0],tree[x][1]);
}
}
void rotate(int x)
{
int y=fa[x],z=fa[y],l=tree[y][1]==x,r=l^1;
if (!isroot(y)) tree[z][tree[z][1]==y]=x;
fa[x]=z; fa[y]=x; fa[tree[x][r]]=y;
tree[y][l]=tree[x][r]; tree[x][r]=y;
pushup(y); pushup(x);
}
void splay(int x)
{
int top=0; s[++top]=x;
for (int i=x;!isroot(i);i=fa[i])
{
s[++top]=fa[i];
}
for (int i=top;i;i--) pushdown(s[i]);
while (!isroot(x))
{
int y=fa[x],z=fa[y];
if (!isroot(y))
{
if (tree[y][0]==x^tree[z][0]==y) rotate(x); else rotate(y);
}
rotate(x);
}
}
void access(int x)
{
int t=0;
while (x)
{
splay(x);
tree[x][1]=t;
t=x; x=fa[x];
}
}
void rever(int x)
{
access(x); splay(x); rev[x]^=1;
}
void link(int x,int y)
{
rever(x); fa[x]=y; splay(x);
}
void cut(int x,int y)
{
rever(x); access(y); splay(y); tree[y][0]=fa[x]=0;
}
int main()
{
n=read();
for (int i=1;i<=n;i++)
{
int x=read();
fa[i]=x+i; size[i]=1;
if (fa[i]>n+1) fa[i]=n+1;
next[i]=fa[i];
}
size[n+1]=1;
m=read();
for (int i=1;i<=m;i++)
{
int f=read();
if (f==1)
{
rever(n+1);
int x=read(); x++;
access(x); splay(x); printf("%d\n",size[tree[x][0]]);
}
else
{
int x=read(),y=read(); x++;
int t=min(n+1,x+y);
cut(x,next[x]); link(x,t); next[x]=t;
}
}
return 0;
}
分块:
#include<iostream>
#include<cstdio>
#include<cmath>
#define N 200005
using namespace std;
int n,m,cnt,block;
int p[N],s[N],k[N],belong[N];
int l[1005],r[1005];
inline int read()
{
int a=0,f=1; char c=getchar();
while (c<'0'||c>'9') {if (c=='-') f=-1; c=getchar();}
while (c>='0'&&c<='9') {a=a*10+c-'0'; c=getchar();}
return a*f;
}
inline int work(int x)
{
int tmp=0;
while (1)
{
tmp+=s[x];
if (!p[x]) break;
x=p[x];
}
return tmp;
}
int main()
{
n=read(); block=(int)(sqrt(n));
for (int i=1;i<=n;i++) k[i]=read();
if (n%block) cnt=n/block+1; else cnt=n/block;
for (int i=1;i<=cnt;i++)
l[i]=(i-1)*block+1,r[i]=i*block;
r[cnt]=n;
for (int i=1;i<=n;i++) belong[i]=(i-1)/block+1;
for (int i=n;i;i--)
if (i+k[i]>n) s[i]=1;
else if (belong[i]==belong[i+k[i]])
s[i]=s[i+k[i]]+1,p[i]=p[i+k[i]];
else s[i]=1,p[i]=i+k[i];
m=read();
while (m--)
{
int f=read(),x=read(),y;
x++;
if (f==1) printf("%d\n",work(x));
else
{
y=read(); k[x]=y;
for (int i=x;i>=l[belong[x]];i--)
if (belong[i]==belong[i+k[i]])
s[i]=s[i+k[i]]+1,p[i]=p[i+k[i]];
else s[i]=1,p[i]=i+k[i];
}
}
return 0;
}