厦门大学 ACM 1466 线段树维护
链接 http://acm.xmu.edu.cn/JudgeOnline/problem.php?id=1466
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<cstring>
#include<vector>
using namespace std;
inline int max( int a,int b ){return (a)>(b)?(a):(b);}
struct date{
int pre,pos;
}temp;
struct date2{
int v,next;
}edge[212345];
struct date3{
int lt,rt,Max;
}node[4123456];
vector<date>s[112345];
int arr[112345],res[1123456],head[112345],N,M,k;
void add_edge( int u,int v ){
edge[k].v = v;
edge[k].next = head[u];
head[u] = k++;
}
void build_tree( int lt,int rt,int t ){
node[t].lt = lt; node[t].rt = rt; node[t].Max = 0;
if( lt == rt ) return ;
int mid = ( lt + rt )>>1;
build_tree( lt,mid,t<<1 );
build_tree( mid+1,rt,t<<1|1 );
}
int update( int pos,int val,int t ){
if( node[t].lt == node[t].rt ) return node[t].Max = val;
if( node[t<<1].rt >= pos ) update( pos,val,t<<1 );
if( node[t<<1|1].lt <= pos )update( pos,val,t<<1|1 );
return node[t].Max = max( node[t<<1].Max,node[t<<1|1].Max );
}
int query( int lt,int rt,int t ){
if( node[t].lt == lt && node[t].rt == rt ) return node[t].Max;
if( node[t<<1].rt >= rt )query( lt,rt,t<<1 );
else if( node[t<<1|1].lt <= lt )query( lt,rt,t<<1|1 );
else{
int a = query( lt,node[t<<1].rt,t<<1 );
int b = query( node[t<<1|1].lt,rt,t<<1|1 );
return max( a,b );
}
}
void DFS( int u,int deep ){
update( deep,arr[u],1 );
int len = s[u].size( );
for( int i = 0; i < len; i++ )
{
int pre = deep - s[u][i].pre;
if( pre <= 0 )res[s[u][i].pos] = -1;
else res[s[u][i].pos] = query( pre,deep,1 );
}
for( int i = head[u]; i != -1; i = edge[i].next )
DFS( edge[i].v,deep+1 );
}
int main( )
{
while( scanf("%d",&N) != EOF )
{
for( int i = 0; i <= N; i++ )s[i].clear( );
for( int i = 1; i <= N; i++ )
scanf("%d",&arr[i]);
int v,k = 0;arr[0] = 0;
memset( head,-1,sizeof(head) );
for( int u = 1; u <= N; u++ )
{
scanf("%d",&v);
add_edge( v,u );
}
scanf("%d",&M);
for( int i = 1; i <= M; i++ )
{
scanf("%d%d",&temp.pre,&v);
temp.pos = i;
s[v].push_back(temp);
}
build_tree( 1,N,1 ); DFS( 0,1 );
for( int i = 1; i <= M; i++ )
if( res[i] == -1 )printf("Wrong request\n");
else printf("%d\n",res[i]);
}
return 0;
}
浙公网安备 33010602011771号