#include<cassert>#include<climits>#include<ctime>#include<iostream>#include<map>usingnamespacestd;template<typenameK,typenameV>structSkipListNode{intlevel;Kkey;Vvalue;SkipListNode**forward;SkipListNode(){}SkipListNode(Kk,Vv,intl,SkipListNode*nxt=NULL){key=k;value=v;level=l;forward=newSkipListNode*[l+1];for(inti=0;i<=l;++i)forward[i]=nxt;}~SkipListNode(){if(forward!=NULL)delete[]forward;}};template<typenameK,typenameV>structSkipList{staticconstexprintMAXL=32;staticconstexprintP=4;staticconstexprintS=0xFFFF;staticconstexprintPS=S/P;staticconstexprintINVALID=INT_MAX;SkipListNode<K,V>*head,*tail;intlength;intlevel;SkipList(){srand(time(nullptr));level=length=0;tail=newSkipListNode<K,V>(INVALID,0,0);head=newSkipListNode<K,V>(INVALID,0,MAXL,tail);}~SkipList(){deletehead;deletetail;}intrandomLevel(){intlv=1;while((rand()&S)<PS)++lv;returnMAXL>lv?lv:MAXL;}voidinsert(constK&key,constV&value){SkipListNode<K,V>*update[MAXL+1];SkipListNode<K,V>*p=head;for(inti=level;i>=0;--i){while(p->forward[i]->key<key){p=p->forward[i];}update[i]=p;}p=p->forward[0];if(p->key==key){p->value=value;return;}intlv=randomLevel();if(lv>level){lv=++level;update[lv]=head;}SkipListNode<K,V>*newNode=newSkipListNode<K,V>(key,value,lv);for(inti=lv;i>=0;--i){p=update[i];newNode->forward[i]=p->forward[i];p->forward[i]=newNode;}++length;}boolerase(constK&key){SkipListNode<K,V>*update[MAXL+1];SkipListNode<K,V>*p=head;for(inti=level;i>=0;--i){while(p->forward[i]->key<key){p=p->forward[i];}update[i]=p;}p=p->forward[0];if(p->key!=key)returnfalse;for(inti=0;i<=level;++i){if(update[i]->forward[i]!=p){break;}update[i]->forward[i]=p->forward[i];}deletep;while(level>0&&head->forward[level]==tail)--level;--length;returntrue;}V&operator[](constK&key){Vv=find(key);if(v==tail->value)insert(key,0);returnfind(key);}V&find(constK&key){SkipListNode<K,V>*p=head;for(inti=level;i>=0;--i){while(p->forward[i]->key<key){p=p->forward[i];}}p=p->forward[0];if(p->key==key)returnp->value;returntail->value;}boolcount(constK&key){returnfind(key)!=tail->value;}};intmain(){SkipList<int,int>L;map<int,int>M;clock_ts=clock();for(inti=0;i<1e5;++i){intkey=rand(),value=rand();L[key]=value;M[key]=value;}for(inti=0;i<1e5;++i){intkey=rand();if(i&1){L.erase(key);M.erase(key);}else{intr1=L.count(key)?L[key]:0;intr2=M.count(key)?M[key]:0;assert(r1==r2);}}clock_te=clock();cout<<"Time elapsed: "<<(double)(e-s)/CLOCKS_PER_SEC<<endl;// about 0.2sreturn0;}