链表心得

来源:互联网 发布:草木知旧阅读题答案 编辑:程序博客网 时间:2024/06/03 13:06

Broken Keyboard,UVa 11988

      输入多组数据。每行数据占一行,包含不超过100000个字母、下划线、字符“[”或者“]”。其中“[”表示home键,“]”表示end键,输入结束标志为文件结束符(EOF)。输入文件不超过5MB。输入每组数据,输出一行,即屏幕上的悲剧文本。

      样例输入:This_is_a_[beiju]_text;

      样例输出:BeijuThis_is_a_text;

      暴力解决肯定超时,所以要用链表做。我们可以定义一个数组s[maxn]表示输入的字符串和数组next[maxn];next[i]表示是s[i]右边真正输出在屏幕上的元素的下坐标。这样就可以运用链表的原理把这道题解出。具体解释看下面代码:

      

   #include <iostream>   #include <cstring>   #include <cstdio>   using namespace std;   const int maxn=100000+5;   int last,cur,next[maxn];/*cur代表实际光标位置,last代表实际文件的最后位置*/   char s[maxn];   int main()   {    while(gets(s+1)!=NULL)        {   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[]是0,这样在调用链表循环时可以使循环终止*/<span style="white-space:pre"></span>                   next[cur]=i;/*给当前的光标赋值到相应数组*/                   if(cur==last)                      last=i;/*更新最后的下坐标*/                   cur=i;/*移动光标*/                }             }          for(int i=next[0];i!=0;i=next[i])             cout<<s[i];          cout<<endl;     }     return 0;}

0 0
原创粉丝点击