链表-单向链表&&UVa 11988 Broken Keyboard(a.k.a.Beijiu Text)(破损的键盘(悲剧文本))
C++最新的2011标准C++11中增加了forward_list,forward_list的设计目标是达到与最好的手写的单向链表数据结构相当的性能。不支持随机访问,没有size操作。不过这个容器在工程上很好,在追求更高的时间空间效率上应该还是手写的好一点,时间开销更小。
新标准库的容器比旧版本快得多,新标准库容器的性能几乎肯定与最精心优化过的同类数据结构一样好(通常会更好)。现代C++程序(当然,同上在追求更高的时间空间效率上应该还是手写的好一点,时间开销更小)应该使用标准库容器。 原因在第470页解释。
From:C++Primer 5th P(292-293)
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
Solution
解决方法来自书上,这里根据自己的理解加了注释。
#include <iostream>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn=100000+5; //每组数据占一行,不超过 100000 个字母、下划线、“[”、"]"
int last,cur,nextt[maxn]; //光标位于cur号字符的后面 reference to next is ambiguous.
char s[maxn];
int main()
{
while(scanf("%s",s+1)==1){
int n=strlen(s+1);//输入保存在s[1],s[2]······中
last=cur=0;
nextt[0]=0;
for(int i=1;i<=n;i++){
char ch=s[i];
if(ch=='[') cur=0;
else if(ch==']') cur=last;
else{
nextt[i]=nextt[cur]; //把现在光标所在位置的编码传给nextt 没有遇到[以前,这里i=cur+1;
nextt[cur]=i;
if(cur==last) last=i; //更新“最后一个字符”编号
cur=i; //移动光标
}
}
for(int i=nextt[0];i!=0;i=nextt[i])
printf("%c",s[i]);
printf("\n");
}
return 0;
}
请看图
谢谢