您的位置:首页 > 其它

UVa 11988 破损的键盘 链表 双向队列

2017-07-09 09:32 375 查看
链表解决

用数组频繁的移动元素效率较低,用链表 较好。

#include<iostream>
#include<cstdio>
#include<cstring>
using namespace std;
int next[100005];
char s[100005];
int main()
{
int last,cur;
//freopen("shujia.txt","r",stdin);
while(scanf("%s",s+1)!=EOF)
{
memset(next,0,sizeof(next));
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;
}


双向队列解决

用双向队列解决,就是每次把 [ ] 内的加在队列首段 ,其他的加在队尾就行了。

#include<iostream>
#include<cstring>
#include<deque>
#include<cstdio>
using namespace std;
char str[100005];
int main()
{
//freopen("shujia.txt","r",stdin);
while(scanf("%s",&str)!=EOF)
{
deque<int >a;
int i=0;
while(str[i]=='['||str[i]=='[')
i++;
a.push_front(i);
while(str[i]!='\0')
{
if(str[i]=='[')
{
a.push_front(i+1);
str[i]='\0';
}
else if(str[i]==']')
{
a.push_back(i+1);
str[i]='\0';
}
i++;
}
while(!a.empty())
{
printf("%s",str+a.front());
a.pop_front();
}
printf("\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: