1. 程式人生 > >連結串列-單向連結串列&&UVa 11988 Broken Keyboard(a.k.a.Beijiu Text)(破損的鍵盤(悲劇文字))的理解與解析

連結串列-單向連結串列&&UVa 11988 Broken Keyboard(a.k.a.Beijiu Text)(破損的鍵盤(悲劇文字))的理解與解析

連結串列-單向連結串列&&UVa 11988 Broken Keyboard(a.k.a.Beijiu Text)(破損的鍵盤(悲劇文字))
C++最新的2011標準C++11中增加了forward_list,forward_list的設計目標是達到與最好的手寫的單向連結串列資料結構相當的效能。不支援隨機訪問,沒有size操作。不過這個容器在工程上很好,在追求更高的時間空間效率上應該還是手寫的好一點,時間開銷更小。 新標準庫的容器比舊版本快得多,新標準庫容器的效能幾乎肯定與最精心優化過的同類資料結構一樣好(通常會更好)。現代C++程式(當然,同上在追求更高的時間空間效率上應該還是手寫的好一點,時間開銷更小)應該使用標準庫容器。  原因在第470頁解釋。                                                                                                                                                               From:C++Primer 5th P(292-293) You’re typing a long text with a broken keyboard. Well it’s not so badly broken. The only problemwith the keyboard is that sometimes the “home” key or the “end” key gets automatically pressed(internally).
You’re not aware of this issue, since you’re focusing on the text and did not even turn on themonitor! After you finished typing, you can see a text on the screen (if you turn on the monitor). In Chinese, we can call it Beiju. Your task is to find the Beiju text.

Input

There are several test cases. Each test case is a single line containing at least one and at most 100,000letters, underscores and two special characters ‘[’ and ‘]’. ‘[’ means the “Home” key is pressedinternally, and ‘]’ means the “End” key is pressed internally.The input is terminated by end-of-file(EOF).

Output

For each case, print the Beiju text on the screen. Sample Input This_is_a_[Beiju]_text [[]][][]Happy_Birthday_to_Tsinghua_University Sample Output BeijuThis_is_a__text Happy_Birthday_to_Tsinghua_University

Solution

解決方法來自書上,這裡根據自己的理解加了註釋。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100000+5;   //每組資料佔一行,不超過 100000 個字母、下劃線、“[”、"]"
int last,cur,nextt[maxn];   //游標位於cur號字元的後面          reference to next is ambiguous.
char s[maxn];


int main()
{
    while(scanf("%s",s+1)==1){
        int n=strlen(s+1);//輸入儲存在s[1],s[2]······中
        last=cur=0;
        nextt[0]=0;

        for(int i=1;i<=n;i++){
            char ch=s[i];
            if(ch=='[') cur=0;
            else if(ch==']') cur=last;
            else{
                nextt[i]=nextt[cur];   //把現在游標所在位置的編碼傳給nextt    沒有遇到[以前,這裡i=cur+1;
                nextt[cur]=i;
                if(cur==last) last=i;  //更新“最後一個字元”編號
                cur=i;  //移動游標
            }
        }
        for(int i=nextt[0];i!=0;i=nextt[i])
            printf("%c",s[i]);
        printf("\n");
    }
    return 0;
}

請看圖
謝謝