Cod sursa(job #500903)

Utilizator tamas_iuliaTamas Iulia tamas_iulia Data 13 noiembrie 2010 16:01:30
Problema Zeap Scor 100
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.84 kb
#include <stdio.h>
#include <algorithm>
#include <set>
#define Nmax 300002
#define INF 2147000000
#define NN 300000
#define INF 2147000000

using namespace std;

char Op[Nmax];
int Arb[Nmax*2],v[Nmax],Nr[Nmax];
set< int > Set;
int N,nrop;
char s[15];

inline int Maxim(int x,int y){ return x>y ? x:y; }
inline int Minim(int x,int y){ return x<y ? x:y; }

inline void Update(int nod,int l,int r,int poz, int val){
	if( l == r ){
		Arb[nod]=val;
		return;
	}
	int m=l+(r-l)/2;
	if( poz <=m ) Update(nod<<1,l,m,poz,val);
	else Update((nod<<1)+1,m+1,r,poz,val);
	
	Arb[nod]=Minim(Arb[nod<<1],Arb[(nod<<1)+1]);
}	

inline void insereaza(int nr){
	int poz,val;
	set< int >:: iterator it;
	if( Set.find(nr) != Set.end() ) return;
	it=Set.upper_bound(nr);  // primul elem mai mare ca nr
	
	if(it != Set.end() ){
		poz=lower_bound(v+1,v+N+1,*it)-v; // pozitia in v
		val=*it-nr;
		Update(1,1,N,poz,val);
	}
	if( it != Set.begin() ){
		poz=lower_bound(v+1,v+N+1,nr)-v;
		val=nr-*(--it);
		Update(1,1,N,poz,val);
	}
	
	Set.insert(nr);
}
inline void sterge(int nr){
	int poz,val;
	set< int >:: iterator it1,it2;
	if( Set.find(nr) != Set.end() ){
		poz=lower_bound(v+1,v+N+1,nr)-v;
		val=INF;
		Update(1,1,N,poz,val);
		Set.erase(nr);
		
		if(Set.empty() ) return;
		it2=Set.upper_bound(nr); 
		it1=it2; --it1;
		if( it2 != Set.begin() && it2!= Set.end() ){
			poz=lower_bound(v+1,v+N+1,*it2)-v;
			val=*it2-*it1;
			Update(1,1,N,poz,val);
		}
		if( it2 == Set.begin() ){
			poz=lower_bound(v+1,v+N+1,*it2)-v;
			val=INF;
			Update(1,1,N,poz,val);
		}
		if( it1 == Set.begin() ){
			poz=lower_bound(v+1,v+N+1,*it1)-v;
			val=INF;
			Update(1,1,N,poz,val);
		}
		
	}
	else printf("%d\n",-1);
}
inline void cauta(int nr){
	if( Set.find(nr) != Set.end() )
		printf("%d\n",1);
	else printf("%d\n",0);
}
inline void max_dif(){
	if( Set.empty() || Set.size()==1 ){
		printf("%d\n",-1);
		return;
	}
	printf("%d\n",*Set.rbegin()-*Set.begin());
}
inline void min_dif(){
	if( Set.empty() || Set.size()==1 ){
		printf("%d\n",-1);
		return;
	}
	
	printf("%d\n",Arb[1]);
}

int main(){
	int i,nr;
	freopen("zeap.in","r",stdin);
	freopen("zeap.out","w",stdout);
	for(i=1;i<Nmax*2;++i) Arb[i]=INF;
	
	while( !feof(stdin) ){
		fgets(s,20,stdin);
		nr=0;
		for(i=0; s[i]>='A' && s[i]<='Z';) ++i;
		for(++i; s[i]>='0' && s[i]<='9';) nr=nr*10+s[i]-'0',++i;
		
		if( s[1]==' ' ) Op[++nrop]=s[0]; // I, S sau C
		else Op[++nrop]=s[2]; // X sau N
		Nr[nrop]=nr; v[nrop]=nr;

		memset(s,0,sizeof(s));
	}
	
	sort(v+1,v+nrop+1);
	N=unique(v+1,v+nrop+1)-v-1;
	
	for(i=1;i<=nrop;++i){
		if(Op[i]=='I') insereaza(Nr[i]);else
		if(Op[i]=='S') sterge(Nr[i]); else
		if(Op[i]=='C') cauta(Nr[i]); else
		if(Op[i]=='X') max_dif();else
		if(Op[i]=='N') min_dif();
		
	}
	
	fclose(stdin); fclose(stdout);
	return 0;
}