要求维护一个 n 个节点的森林,实现 m 个询问,其中包括
n<200,000
m<100,000
动态树的入门题。
只需要实现 access 操作以及维护子树大小 size 即可。
其实我做这道题是为了找找写动态树的感觉,发现了不少要注意的细节。
总结地说,越是基本的函数就越不能打错,不然就要花好多的时间去查出来。
附上代码:
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
#include
using namespace std;
typedef double db;
typedef long long LL;
typedef pair< int, int > PII;
typedef pair< LL, LL > PLL;
typedef pair< db, db > PDD;
const db dInf = 1E90;
const LL lInf = ( LL ) 1E16;
const int Inf = 0x23333333;
const int N = 200005;
#define it iterator
#define rbg rbegin()
#define ren rend()
#define bg begin()
#define en end()
#define sz size()
#define fdi( i, x ) for ( typeof( x.rbg ) i=x.rbg; i!=x.ren; ++i )
#define foi( i, x ) for ( typeof( x.bg ) i=x.bg; i!=x.en; ++i )
#define fd( i, y, x ) for ( int i=( y )-1, lim=x; i>=lim; --i )
#define fo( i, x, y ) for ( int i=x, lim=y; i
#define mkp( A, B ) make_pair( A, B )
#define pub( x ) push_back( x )
#define pob( x ) pop_back( x )
#define puf( x ) push_front( x )
#define pof( x ) pop_front( x )
#define fi first
#define se second
namespace LCT
{
struct node
{
node () : size( 1 ) {}
int fa, s[2];
int size;
} a[N];
inline bool top( const int &x )
{
int z = a[x].fa;
return ( !z ) || a[z].s[0]!=x && a[z].s[1]!=x;
}
inline bool dir( const int &x )
{
int z = a[x].fa;
return ( a[z].s[1] == x );
}
inline void update( const int &x )
{
a[x].size = 1;
fo ( k, 0, 2 ) a[x].size += a[ a[x].s[k] ].size;
}
inline void rotate( const int &x )
{
int y = a[x].fa, z = a[y].fa, p = dir( x );
int q = p ^ 1, A = a[x].s[q];
if ( !top( y ) ) a[z].s[ dir( y ) ] = x;
a[y].fa = x, a[y].s[p] = A, update( y );
a[x].fa = z, a[x].s[q] = y;
if ( A ) a[A].fa = y;
}
inline void splay( const int &x )
{
while ( !top( x ) )
{
int y = a[x].fa, z = a[y].fa;
if ( !z || top( z ) || dir( y )^dir( x ) ) rotate( x );
else rotate( y ), rotate( x );
}
update( x );
}
inline void expose( const int &x )
{
for ( int _x=x, y=0; _x; _x=a[_x].fa )
splay( _x ), a[_x].s[0] = y, y = _x;
splay( x );
}
inline void link( const int &x, const int &y )
{
expose( y ), a[y].fa = x;
}
inline void cut( const int &x, const int &y )
{
expose( y ), splay( x ), a[x].s[0] = a[y].fa = 0;
}
inline int query( const int &x )
{
expose( x );
return a[x].size;
}
}
int faict[N];
int n;
void preprocessing()
{
LCT :: a[0].size = 0;
LL temp;
cin >> n; ++n;
fo ( i, 1, n )
{
cin >> temp; faict[i] = ( int ) min( temp, ( LL ) n - i );
if ( i + faict[i] < n ) LCT :: link( i + faict[i], i );
}
}
void solve()
{
int T, type, x;
LL temp;
cin >> T;
fo ( Case, 0, T )
{
cin >> type >> x; ++x;
if ( type==2 )
{
cin >> temp;
if ( x + faict[x] < n ) LCT :: cut( x + faict[x], x );
faict[x] = ( int ) min( temp, ( LL ) n-x );
if ( x + faict[x] < n ) LCT :: link( x + faict[x], x );
}
else cout << LCT :: query( x ) << endl;
}
}
int main()
{
ios :: sync_with_stdio( 0 );
preprocessing();
solve();
return 0;
}