UVA 11988 Broken Keyboard (a.k.a. Beiju Text)(破損的鍵盤(又名:悲劇的文本))(鏈表)

Question:
Broken Keyboard (a.k.a. Beiju Text)
You’re typing a long text with a broken keyboard. Well it’s not so badly broken. The only problem with 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 the monitor! 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,000 letters, underscores and two special characters ‘[’ and ‘]’. ‘[’ means the “Home” key is pressed internally, and ‘]’ means the “End” key is pressed internally. The input is terminated by end-of-file (EOF). The size of input file does not exceed 5MB.

Output
For each case, print the Beiju text on the screen.

Sample Input
This_is_a_[Beiju]_text
[[]][][]Happy_Birthday_to_Tsinghua_University
Output for the Sample Input
BeijuThis_is_a__text
Happy_Birthday_to_Tsinghua_University
Rujia Liu’s Present 3: A Data Structure Contest Celebrating the 100th Anniversary of Tsinghua University
Special Thanks: Yiming Li
Note: Please make sure to test your program with the gift I/O files before submitting!

題目大意:一個鍵盤出了問題,Home鍵和End鍵故障,會時不時彈出,你要把悲劇的文本找出來
解題思路:當遇到‘[]’符號時要推’[]’中的內容至屏幕最左邊。可用鏈表,並在字符最前面添加虛擬字符,cur表示光標的位置,cur表示光標位於s[cur]的右邊還需一個last表示最後一個字符
(https://www.bnuoj.com/v3/contest_show.php?cid=8307#problem/D)

#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;
const int maxn=1e5+5;
char s[maxn];
int next1[maxn],cur,last;
int main()
{
    while (~scanf("%s",s+1))  //將字符串儲存在是s[1],s[2]...中
    {
        memset(next1,0,sizeof(next1));
        int len=strlen(s+1);
        cur=last=0;
        next1[0]=0;
        for(int i=1;i<=len;i++)
        {
            if(s[i]=='[')  cur=0;   //當其遇到'['字符時,應輸出在最前面,cur=0
            else if(s[i]==']')   cur=last;  //當其遇到']'字符時,說明內容已經處理完畢,應當返回處理前的位置
            else
            {
                next1[i]=next1[cur];  //方便儲存完了特殊內容後連接原來順序的內容,例如:next[4]是第一個特殊內容中的第一個字母next[4]=next[0]=1;這樣輸完了特殊內容後會按原來的順序繼續輸出
                next1[cur]=i;   //next[0]=4這樣就會先輸出第4個字母了
                if(last==cur) last=i; //更新最後一個字母
                cur=i; //光標移動
            }
        }
        for(int i=next1[0];i!=0;i=next1[i])
            printf("%c",s[i]);
        printf("\n");
    }
    return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章