Splay C++ 二叉链存图Re
查看原帖
Splay C++ 二叉链存图Re
171528
syr050301楼主2021/5/30 11:55

改了两天了

还是一直 程序已停止工作

求助QAQ

报错部分在 Rotate 函数中

bool Rotate(Node*& u){
	Node* f = u->father;
	Node* ff = f->father;
	
	if(ff->lchild == f) ff->lchild = u;
	else ff->rchild = u;
	u->father = ff;
	
	if(f->lchild == u){
		f->lchild = u->rchild;
		if(f->lchild != NULL) f->lchild->father = f;
		u->rchild = f;
	}
	else{
		f->rchild = u->lchild;
		if(f->rchild != NULL) f->rchild->father = f;
		u->lchild = f;
	}
	
	f->father = u;
	Update(f);
	Update(u);
}

全部的代码 Code:

#include<bits/stdc++.h>
#define N 100005
using namespace std;

long long Read(){
	long long x,f=1;
	char ch = getchar();
	for(;!isdigit(ch);ch=getchar()) if(ch=='-') f=-1;
	for(;isdigit(ch);ch=getchar()) x=x*10+ch-'0';
	return x*f;
}

struct SplayTreeNode{
	int val,cnt,size;
	SplayTreeNode *lchild,*rchild,*father;
	SplayTreeNode(int v,int c,int s,SplayTreeNode* fa){
		val = v;
		cnt = c;
		size = s;
		lchild = NULL;
		rchild = NULL;
		father = fa;
	}
};


class SplayTree{
	typedef SplayTreeNode Node;

public:
	
	bool Insert(const int& x){
		return Insert_(root_father,root,x);
	}
	
	bool Splay(Node*& u,Node*& goal){
		while(u->father != goal){
			Node* f = u->father;
			Node* ff = f->father;
			if(ff != goal)
				(ff->lchild == f)^(f->lchild == u) ? Rotate(u) : Rotate(f);
			Rotate(u);
		}
		if(goal == root_father)
			root = u;
	}

	void Output(){
		Output_(root);
		cout << endl;
	}
	
private:
	Node* root_father = new Node(-1,0,0,NULL);
	Node* root = NULL;
	
	bool Insert_(Node*& fa,Node*& u,const int& x){
		if(u == NULL){
			u = new SplayTreeNode(x,1,1,fa);
			return Splay(u,root_father);
		}
		if(u->val < x)
			return Insert_(u,u->rchild,x);
		if(u->val > x)
			return Insert_(u,u->lchild,x);
		if(u->val == x){
			u->cnt++;
			return Splay(u,root_father);
		}
	}
	
	bool Rotate(Node*& u){
		Node* f = u->father;
		Node* ff = f->father;
		
		if(ff->lchild == f) ff->lchild = u;
		else ff->rchild = u;
		u->father = ff;
		
		if(f->lchild == u){
			f->lchild = u->rchild;
			if(f->lchild != NULL) f->lchild->father = f;
			u->rchild = f;
		}
		else{
			f->rchild = u->lchild;
			if(f->rchild != NULL) f->rchild->father = f;
			u->lchild = f;
		}
		
		f->father = u;
		Update(f);
		Update(u);
	}
	
	void Update(Node*& u){
		u->size = u->lchild->size + u->rchild->size + u->cnt;
	}
	
	void Output_(Node*& u){
		if(u == NULL) return;
		else{
			Output_(u->lchild);
			cout << u->val << " ";
			Output_(u->rchild);
		}
	}	
};

int main(){
	SplayTree x;
	int n,tot;
	cin >> n;
	for(int i = n;n > 0;n--){
		cin >> tot;
		x.Insert(tot);
	}
	x.Output();
	return 0;
}
2021/5/30 11:55
加载中...