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

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

#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;
}

posted @ 2017-07-09 09:33  南风古  阅读(115)  评论(0编辑  收藏  举报