#队列 or 链表#洛谷 2776 codevs 5183 小组队列

题目

poj 2259


队列代码

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
queue<int>q[301]; int n,a[100001];
int in(){
    int ans=0; char c=getchar();
    while (c<48||c>57) c=getchar();
    while (c>47&&c<58) ans=ans*10+c-48,c=getchar();
    return ans;
}
int main(){
    n=in(); in();
    for (int i=1;i<=n;i++) a[i]=in()+1;
    int t=in();
    while (t--){
        char c=getchar(); while (c<97||c>122) c=getchar();//一定要这样做
        c=getchar(); bool flag=0;
        if (c=='u') flag=1;
        while (c>96&&c<123) c=getchar();
        if (flag){
            int x=in()+1;
            q[a[x]].push(x);//插入
            if (q[a[x]].size()==1) q[0].push(a[x]);//大队列中插入新的编号
        }
        else{
            printf("%d\n",q[q[0].front()].front()-1);//输出
            q[q[0].front()].pop();//出队
            if (q[q[0].front()].empty()) q[0].pop();//从大队列中弹出编号
        }
    }
    return 0;
}

链表代码(可以发现在队列中运用的在链表内亦能实现)

#include <cstdio>
#include <queue>
#include <cstring>
using namespace std;
int n,a[100000],head[300],ls[100000][2],m=1,l=1,t1;
int in(){
    int ans=0; char c=getchar();
    while (c<48||c>57) c=getchar();
    while (c>47&&c<58) ans=ans*10+c-48,c=getchar();
    return ans;
}
int main(){
    n=in(); in();
    for (int i=0;i<n;i++) a[i]=in();
    int t=in();
    while (t--){
        char c=getchar(); while (c<97||c>122) c=getchar();
        c=getchar(); bool flag=0;
        if (c=='u') flag=1;
        while (c>96&&c<123) c=getchar();
        if (flag){
            int x=in();
            ls[m][0]=x;//当前位置为x
            if (!head[a[x]]) t1=m,ls[t1][1]=++m;//没有人需要创建小组
            else{
                ls[t1][1]++; ls[m][1]=ls[head[a[x]]][1];//创建链表
                if (t1==head[a[x]]) t1=m;//到最后一个元素
                ls[head[a[x]]][1]=m++;//指向上一个位置
            }
            head[a[x]]=m-1;//那么头就是m-1的地方
        }
        else{
            printf("%d\n",ls[l][0]);//l是第一个位置(初始为1)
            if (head[a[ls[l][0]]]==l) head[a[ls[l][0]]]=0;//当前小组没人了
            l=ls[l][1];//下一个人
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/sugar_free_mint/article/details/81700017