用的是POJ3481的例子:对应PPT注意一下其中的写法#include <iostream> #define MAX 100 struct Node { int key;//这里的key就是优先级P int num;//这里的num代表client的标号K Node* parent; Node* leftChild; Node* rightChild; Node() {//构造函数 key = 0; num = 0; parent = leftChild = rightChild; } }; Node NIL; Node* nil = &NIL; Node NodePool[MAX]; int offset = 0; Node* newNode() { NodePool[offset].key = 0; NodePool[offset].parent = NodePool[offset].leftChild = NodePool[offset].rightChild = nil; return NodePool + (offset++); } struct BinarySearchTree{ Node* root = nil; Node* search(Node* node, int key) { while(nil!=node&&node->key!=key){ if(key<node->key){ node = node->leftChild; } else if(key>node->key){ node = node->rightChild; } } return node; } Node* minimum(Node* node) { while(node!=nil&&node->leftChild!=nil){ node = node->leftChild; } return node; } Node* maximum(Node* node) { while(node!=nil&&node->rightChild!=nil){ node = node->rightChild; } return node; } Node* predecessor(Node* node) { if(node->leftChild!=nil){ return maximum(node->leftChild); } else{ while(nil!=node->parent&&node == node->parent->leftChild){ node = node->parent; } } return node->parent; } Node* successor(Node* node) { if(node->rightChild!=nil){ return minimum(node->rightChild); } else{ while(nil!=node->parent&&node==node->parent->rightChild){ node = node ->parent; } } return node->parent; } void insert(Node* node) { Node* father = nil; Node* current = root; while (nil != current) { father = current; if (node->key < current->key) { current = current->leftChild; } else { current = current->rightChild; } } node->parent = father; if (nil == father) { root = node; } else if (node->key < father->key) { father->leftChild = node; } else { father->rightChild = node; } } void transplant(Node* des, Node* src) { if (nil == des->parent) { root = src; } else if (des == des->parent->leftChild) { des->parent->leftChild = src; } else { des->parent->rightChild = src; } if (nil != src) { src->parent = des->parent; } } void del(Node* node) { if (nil == node->leftChild) { transplant(node, node->rightChild); } else if (nil == node->rightChild) { transplant(node, node->leftChild); } else { Node* suc = minimum(node->rightChild); if (suc->parent != node) { transplant(suc, suc->rightChild); suc->rightChild = node->rightChild; suc->rightChild->parent = suc; } transplant(node, suc); suc->leftChild = node->leftChild; suc->leftChild->parent = suc; } } }; int main(){ freopen("input.txt","r",stdin); int cmd; BinarySearchTree Tas; Tas.root = nil; while(scanf("%d",&cmd)&&cmd!=0){ Node* p = newNode(); switch(cmd){ case 1: scanf("%d %d",&p->num,&p->key); Tas.insert(p); break; case 2: p = Tas.maximum(Tas.root); if(p==nil){printf("0\n");break;} printf("%d\n",p->num); Tas.del(p); break; case 3: p = Tas.minimum(Tas.root); if(p==nil){printf("0\n");break;} printf("%d\n",p->num); Tas.del(p); break; } } return 0; }
时间: 2024-10-13 12:27:05