POJ 2828

中间迷途了好久,渐渐走回正轨。
这道题卡的很死,用g++会TLE但是c++就A了。
思路是利用splay tree,不过公认好方法应该是线段树,用splay耗时3000ms左右,线段树仅2000ms

#include <iostream>
#include <algorithm>
#include <queue>
#include <string>
#include <vector>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <string>
#include <stack>
#include <map>
#include <set>
#include <deque>
using namespace std;

const int maxn= 2e5+5;

struct Node;
Node *null;
struct Node
{
	Node *ch[2], *fa;
	int size, v;
	void pushUp()
	{
		if (this== null){
			return;
		}
		size= ch[0]->size+ch[1]->size+1;
	}
	void clear()
	{
		size= 1;
		ch[0]= ch[1]= fa= null;
	}
	void setc(Node *x, int d)
	{
		if (this== null){
			return;
		}
		ch[d]= x;
		x->fa= this;
	}
	int d()
	{
		return fa->ch[1]== this;
	}
};
int n, p, v;
int cnt;
Node pool[maxn], *tail, *root;

void Rotate(Node *x)
{
	if (x->fa== null){
		return;
	}
	Node *f= x->fa, *ff= x->fa->fa;
	int c= x->d(), cc= f->d();
	f->setc(x->ch[!c], c);
	x->setc(f, !c);
	if (ff->ch[cc]== f){
		ff->setc(x, cc);
	}
	else{
		x->fa= ff;
	}
	f->pushUp();
}
void Splay(Node *&root, Node *x, Node *goal)
{
	while (x->fa!= goal){
		if (x->fa->fa== goal){
			Rotate(x);
		}
		else{
			int c= x->d(), cc= x->fa->d();
			c== cc ? Rotate(x->fa) : Rotate(x);
			Rotate(x);
		}
	}
	x->pushUp();
	if (null== goal){
		root= x;
	}
}
Node *get_kth(Node *r, int k)
{
	if (null== r){
		return r;
	}
	Node *x= r;
	while (x->ch[0]->size+1!= k){
		if (k<= x->ch[0]->size){
			x= x->ch[0];
		}
		else{
			k-= x->ch[0]->size+1;
			x= x->ch[1];
		}
	}

	return x;
}
void PrintAns(Node *r)
{
	if (r== null || -1== r->v){
		return;
	}
	PrintAns(r->ch[0]);
	if (++cnt> 1){
		putchar(' ');
	}
	printf("%d", r->v);
	PrintAns(r->ch[1]);
}

int main(int argc, char const *argv[])
{
	while (~scanf("%d", &n)){
		Node *cur;
		null= tail= pool;
		null->ch[0]= null->ch[1]= null->fa= null;
		null->size= null->v= 0;

		cur= ++tail;
		cur->clear();
		cur->v= -1;
		root= cur;

		for (int i= 0; i< n; ++i){
			scanf("%d %d", &p, &v);
			cur= ++tail;
			cur->clear();
			cur->v= v;
			Splay(root, get_kth(root, p+1), null);
			if (root->ch[1]== null){
				root->setc(cur, 1);
				root->pushUp();
			}
			else{
				Node *now= root->ch[1], *pre= root;
				while (now!= null){
					pre= now;
					now= now->ch[0];
				}
				pre->setc(cur, 0);
				Splay(root, cur, null);
			}
		}

		cnt= 0;
		PrintAns(root);
		putchar('\n');
	}

	return 0;
}
上一篇:POJ 3264


下一篇:POJ 2186