11988 - Broken Keyboard (a.k.a. Beiju Text)

来源:互联网 发布:数组方法和字符串方法 编辑:程序博客网 时间:2024/05/16 04:46

You're typing along text with a broken keyboard. Well it's not so badly broken. The onlyproblem with the keyboard is that sometimes the "home" key or the"end" key gets automatically pressed (internally).

You're not awareof 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 youturn on the monitor).

In Chinese, we cancall it Beiju. Your task is to find the Beiju text.

Input

There are severaltest cases. Each test case is a single line containing at least one and at most100,000 letters, underscores and two special characters '[' and ']'. '[' meansthe "Home" key is pressed internally, and ']' means the"End" key is pressed internally. The input is terminated byend-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 theSample Input

BeijuThis_is_a__text

Happy_Birthday_to_Tsinghua_University

代码:

方法一(逆向思维)

#include<iostream>

#include<string>

using namespacestd;

 

int main()

{

    string s;

    while(getline(cin,s))

    {

        int n=s.size();

        for(int i=n-1;i>=0;i--)

        {

            if(s[i]=='[')

            {

                for(intj=i+1;j<n&&s[j]!=']';j++)

                {

                    cout<<s[j];

                    s[j]=']';

                }

                s[i]=']';

            }

        }

        for(int i=0;i<n;i++)

        {

            if(s[i]!=']')

            {

                cout<<s[i];

            }

        }

        cout<<endl;

    }

    return 0;

}

解析:

从后向前遍历,遇到’[’后向后输出直至遇见’]’或者到达字符串的末尾,每次输出完以后,将’[’及输出的所有字符变为’]’;遍历完成后,从头再次遍历,遇见非’]’字符,就输出,即可得到结果.

方法二(数据结构:链表模拟)实在没看懂

// UVa11988 BrokenKeyboard

// Rujia Liu

#include<cstdio>

#include<cstring>

const int maxn =100000 + 5;

int last, cur,next[maxn]; // 光标位于cur号字符之后面

char s[maxn];

 

int main() {

  while(scanf("%s", s+1) == 1) {

    int n = strlen(s+1); // 输入保存在s[1], s[2]...中

    last = cur = 0;

    next[0] = 0;

 

    for(int i = 1; i <= n; i++) {

      char ch = s[i];

      if(ch == '[') cur = 0;

      else if(ch == ']') cur = last;

      else {

        next[i] = next[cur];

        next[cur] = i;

        if(cur == last) last = i; // 更新“最后一个字符”编号

        cur = i; // 移动光标

      }

    }

    for(int i = next[0]; i != 0; i = next[i])

      printf("%c", s[i]);

    printf("\n");

  }

  return 0;

}

si-font��iy@� mso-hansi-theme-font:minor-latin'>从上往下dfs

                break;

            }

        }

        if(ok)

        {

           cout<<"0.00"<<fixed<<setprecision(2)<<""<<Left<<" "<< W<<""<<Right<<endl;

        }

        else

        {

           cout<<"IMPOSSIBLE\n";

        }

    }

    return 0;

}

0 0
原创粉丝点击