UVA11988 Broken Keyboard 链表

题目描述:

你在输入文章的时候,键盘上的Home键和End键出了问题,会不定时的按下。

给你一段按键的文本,其中'['表示Home键,']'表示End键,输出这段悲剧的文本。


解题思路

用顺序结构储存会超时 所以用模拟链表来储存

cur表示光标的位置 last表示当前最后一个字符的编号 next[i]表示s[i]后面的字符的编号 为了方便起见在数组的最前面虚拟一个s[0]。代码如下

#include 
#include 
#include 
using namespace std;
const int maxn = 100005;
char s[maxn];
int last,cur,next[maxn];
int main()
{
    while(scanf("%s",s+1) == 1) {
        int n = strlen(s+1);
        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;
}

你可能感兴趣的:(算法与数据结构/ACM)