Tree 倍增

每个节点有重量,询问节点的祖先序列中最长重量递增序列长度

赛中写的倍增没调出来,感觉这种从指数最大到最小枚举做倍增的方法也不错

比之前那个从每次都从低位开始凑的更快

//#include<bits/stdc++.h>  
//#pragma comment(linker, "/STACK:1024000000,1024000000")   
#include<stdio.h>  
#include<algorithm>  
#include<queue>  
#include<string.h>  
#include<iostream>  
#include<math.h>                    
#include<set>  
#include<map>  
#include<vector>  
#include<iomanip> 
#include<bitset>
using namespace std;         //

#define ll long long  
#define pb push_back  
#define FOR(a) for(int i=1;i<=a;i++) 
#define sqr(a) (a)*(a)
#define dis(a,b) sqrt(sqr(a.x-b.x)+sqr(a.y-b.y))
ll qp(ll a,ll b,ll mod){
	ll t=1;while(b){if(b&1)t=t*a%mod;b>>=1;a=a*a%mod;}return t;
}
struct DOT{ll x;ll y;};
inline void read(int &x){int k=0;char f=1;char c=getchar();for(;!isdigit(c);c=getchar())if(c=='-')f=-1;for(;isdigit(c);c=getchar())k=k*10+c-'0';x=k*f;} 
const int dx[4]={0,0,-1,1};
const int dy[4]={1,-1,0,0};
const int inf=0x3f3f3f3f; 
const ll Linf=0x3f3f3f3f3f3f3f3f;
const ll mod=1e9+7;

const int maxn=4e5+5;

int fa[maxn][50];	//i的2^j级别父亲
ll fasum[maxn][50];	
ll w[maxn];

ll query(ll id,ll lim){
	int ans=0;
	for(int i=32;i>=0;i--){
		if(fasum[id][i]<=lim){
			lim-=fasum[id][i];
			ans+=1<<i;
			id=fa[id][i];
		}
	}
	printf("%d\n",ans);
	return 1ll*ans;
}

int Q;
int main(){
	scanf("%d",&Q);
	ll lst=0;
	int cnt=1;	//节点数

	w[0]=Linf;
	for(int i=0;i<=32;i++)fa[1][i]=0;
	for(int i=0;i<=32;i++)fasum[0][i]=Linf;
	for(int i=1;i<=32;i++)fasum[1][i]=Linf;

	while(Q--){
		int op;ll p,q;
		scanf("%d%lld%lld",&op,&p,&q);
		p^=lst;q^=lst;
		
		if(op==1){
			w[++cnt]=q;
			if(w[p] >= w[cnt])fa[cnt][0]=p;
			else{
				for(int i=32;i>=0;i--){
					int nt=fa[p][i];
					if(w[nt] < w[cnt])p=nt;
				}
				fa[cnt][0]=fa[p][0];
			}	
			for(int i=1;i<=32;i++)fa[cnt][i]=fa[fa[cnt][i-1]][i-1];
			fasum[cnt][0]=w[cnt];
			for(int i=1;i<=32;i++)fasum[cnt][i]=min(Linf,
					fasum[cnt][i-1] 
					+ 
					fasum[fa[cnt][i-1]][i-1]
					);
		}else if(op==2){
			lst=query(p,q);	//p开始,总重q以内
		}
	}
}

posted @ 2018-02-16 02:31  Drenight  阅读(117)  评论(0编辑  收藏  举报