UVA11988 Broken Keyboard (a.k.a. Beiju Text)【输入输出】

UVA11988 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 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


问题链接UVA11988 Broken Keyboard (a.k.a. Beiju Text)

问题简述:参见上文。

问题分析破损的键盘,字符串中的字符"["相当于"Home"键(光标跳到输入行的开始),字符"]"相当于"End"键(光标跳到输入行的结束)。

程序说明

使用数组nexti[],nexti[i]=n表示s[i]右边的字符为s[n]。

程序的关键是设置数组nexti[]各个元素值,该数组如同一个链表一般。

题记:目前的计算机内存地址是一维线性编码的,所以如果能用数组来表示问题,计算速度相对较快。

AC的C++语言程序如下:

/* UVA11988 Broken Keyboard (a.k.a. Beiju Text)  */

#include <iostream>
#include <stdio.h>

using namespace std;

const int N = 100000 + 2;
char s[N];
int nexti[N];

int main()
{
    int current, last;

    while(fgets(s+1, N, stdin) != NULL) {
        current = last = 0;
        nexti[0] = 0;
        int i = 1;
        while(s[i] != '
') {
            if(s[i] == '[')
                current = 0;
            else if(s[i]==']')
                current = last;
            else {
                nexti[i] = nexti[current];
                nexti[current] = i;
                if(last == current)
                    last = i;
                current = i;
            }
            i++;
       }

        for(i = nexti[0]; i; i = nexti[i])
            printf("%c", s[i]);
        putchar('
');
    }

    return 0;
}