题目链接
很明显,如果和下一个弹到的节点连接一条边的话,那么就会形成一棵森林,我们要求的答案实际上就是它父亲节点的个数+1,但是维护一个森林,我们还需要存储每个森林的位置,比较的麻烦了,所以我们不妨开一个点,作为超级点,将所有的森林连接起来,那么现在的答案就是它到超级节点连接的边的个数了,实际上就是节点数-1,于是就可以利用LCT进行维护了。
#include <iostream>
#include <cstdio>
#include <cmath>
#include <string>
#include <cstring>
#include <algorithm>
#include <limits>
#include <vector>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <bitset>
#include <unordered_map>
#include <unordered_set>
#define lowbit(x) ( x&(-x) )
#define pi 3.141592653589793
#define e 2.718281828459045
#define INF 0x3f3f3f3f
#define HalF (l + r)>>1
#define lsn rt<<1
#define rsn rt<<1|1
#define Lson lsn, l, mid
#define Rson rsn, mid+1, r
#define QL Lson, ql, qr
#define QR Rson, ql, qr
#define myself rt, l, r
using namespace std;
typedef unsigned long long ull;
typedef unsigned int uit;
typedef long long ll;
const int maxN = 2e5 + 7;
int N, Q;
namespace LCT
{
int fa[maxN], c[maxN][2];
int r[maxN], siz[maxN];
void clear(int x) { r[x] = siz[x] = c[x][0] = c[x][1] = fa[x] = 0; }
bool isroot(int x) { return c[fa[x]][0] != x && c[fa[x]][1] != x; }
void pushup(int x)
{
siz[x] = siz[c[x][0]] + siz[c[x][1]] + 1;
}
void pushr(int x) { swap(c[x][0], c[x][1]); r[x] ^= 1; }
void pushdown(int x)
{
if(r[x])
{
if(c[x][0]) pushr(c[x][0]);
if(c[x][1]) pushr(c[x][1]);
r[x] = 0;
}
}
void Rotate(int x)
{
int y = fa[x], z = fa[y], k = c[y][1] == x;
if(!isroot(y)) c[z][c[z][1] == y] = x;
fa[x] = z;
c[y][k] = c[x][k ^ 1];
fa[c[x][k ^ 1]] = y;
c[x][k ^ 1] = y;
fa[y] = x;
pushup(y);
pushup(x);
}
int Stap[maxN];
void Splay(int x)
{
int y = x, z = 0;
Stap[++z] = y;
while(!isroot(y)) Stap[++z] = y = fa[y];
while(z) pushdown(Stap[z--]);
while(!isroot(x))
{
y = fa[x]; z = fa[y];
if(!isroot(y)) (c[z][0] == y) ^ (c[y][0] == x) ? Rotate(x) : Rotate(y);
Rotate(x);
}
}
void Access(int x)
{
int y = 0;
while(x)
{
Splay(x);
c[x][1] = y;
pushup(x);
y = x;
x = fa[x];
}
}
void makeroot(int x)
{
Access(x);
Splay(x);
pushr(x);
}
int findroot(int x)
{
Access(x);
Splay(x);
while(c[x][0])
{
pushdown(x);
x = c[x][0];
}
Splay(x);
return x;
}
void Split(int x, int y)
{
makeroot(x);
Access(y);
Splay(y);
}
void link(int x, int y)
{
makeroot(x);
if(findroot(y) != x)
{
fa[x] = y;
}
}
void cut(int x, int y)
{
makeroot(x);
if(findroot(y) != x || fa[y] != x || c[y][0]) return;
fa[y] = c[x][1] = 0;
pushup(x);
}
};
using namespace LCT;
int a[maxN];
int main()
{
scanf("%d", &N);
for(int i=0; i<=N + 1; i++) clear(i);
for(int i=1; i<=N; i++)
{
scanf("%d", &a[i]);
if(i + a[i] <= N)
{
link(i, i + a[i]);
}
else
{
link(i, N + 1);
}
}
scanf("%d", &Q);
for(int i=1, op, x, y; i<=Q; i++)
{
scanf("%d%d", &op, &x); x++;
if(op == 1)
{
Split(N + 1, x);
printf("%d\n", siz[x] - 1);
}
else
{
if(x + a[x] > N)
{
cut(x, N + 1);
}
else
{
cut(x, x + a[x]);
}
scanf("%d", &y);
if(x + y > N)
{
link(x, N + 1);
}
else
{
link(x, x + y);
}
a[x] = y;
}
}
return 0;
}