早苗入手了最新的高級打字機。最新款天然有着與以往不一樣的功能,那就是它具有撤銷功能,厲害吧。html
請爲這種高級打字機設計一個程序,支持以下3種操做:算法
1.T x:在文章末尾打下一個小寫字母x。(type操做)ide
2.U x:撤銷最後的x次修改操做。(Undo操做)post
(注意Query操做並不算修改操做)spa
3.Q x:詢問當前文章中第x個字母並輸出。(Query操做)設計
文章一開始能夠視爲空串。指針
輸入格式:code
第1行:一個整數n,表示操做數量。視頻
如下n行,每行一個命令。保證輸入的命令合法。htm
輸出格式:
每行輸出一個字母,表示Query操做的答案。
7 T a T b T c Q 2 U 2 T c Q 2
b c
【數據範圍】
對於40%的數據 n<=200;
對於100%的數據 n<=100000;保證Undo操做不會撤銷Undo操做。
<高級挑戰>
對於200%的數據 n<=100000;Undo操做能夠撤銷Undo操做。
<IOI挑戰>
必須使用在線算法完成該題。
主席樹前置技能點——可持久化線段樹。教學視頻看這裏。我已經搞不清主席樹和可持久化線段樹的關係了。常見的說法就是這二者是同一個東西,可是有些地方又說主席樹專指解決區間第k大問題的可持久化線段樹,據說當時是HJT方太96主席不會劃分樹,因而搞出了一個用可持久化權值線段樹解決此問題的方法,比劃分樹、歸併樹更優秀,我的以爲這個說法更靠譜。
2019年7月27日09:10:55更新 Seter的博客,主席樹歷史
#include<stdio.h> int n; struct tree{ int l,r;//左右兒子指針 char cc; }t[4000010]; int root[100010]={0},cnt=1; int len[100010]={0}; void updata(int & now,int last,int l,int r,int pos,char c) { now=cnt++; t[now].l=t[last].l;t[now].r=t[last].r; if(l==r) { t[now].cc=c; return; } int mid=l+r>>1; if(pos>mid) updata(t[now].r,t[last].r,mid+1,r,pos,c); else updata(t[now].l,t[last].l,l,mid,pos,c); } void query(int now,int l,int r,int pos) { if(l==r) { printf("%c\n",t[now].cc); return; } int mid=l+r>>1; if(pos>mid) query(t[now].r,mid+1,r,pos); else query(t[now].l,l,mid,pos); } int main() { scanf("%d",&n); int t=0; for(int kkk=1;kkk<=n;kkk++) { char mode[3]; scanf("%s",mode); if(mode[0]=='T') { scanf("%s",mode); t++; len[t]=len[t-1]+1; updata(root[t],root[t-1],1,n,len[t],mode[0]); } else if(mode[0]=='U') { int x; scanf("%d",&x); root[t+1]=root[t-x]; len[t+1]=len[t-x]; t++; } else { int pos; scanf("%d",&pos); query(root[t],1,n,pos); } } return 0; }