山理工2135 隊列 排隊買飯

單純用隊列不好模擬中間離隊的人,因爲隊列只能取隊首元素

所以用一維數組模擬隊列

#include <iostream>
#include<stdio.h>
#include<string.h>
using namespace std;
int main()
{
    char s[10];
    int a[10050];
    int i,j,k,m,n,begin,end,x;
    scanf("%d",&m);
    for(i=0;i<=m-1;i++)
    {
        scanf("%d",&a[i]);
    }
    begin=0;end=m;     //begin記錄隊首的下標,end記錄隊尾往後一個的下標
    scanf("%d",&n);
    while(n--)
    {
        scanf("%s",s);
        if(strcmp(s,"LENGTH")!=0)
            scanf("%d",&x);
        if(strcmp(s,"JOIN")==0)
        {
            a[end++]=x; //有人入隊,end後移
        }
        if(strcmp(s,"FINISH")==0)
        {
            while(x--)
                begin++;    //有人買完飯,begin後移
        }
        if(strcmp(s,"ASK")==0)
        {
            printf("%d\n",a[begin+x-1]);
        }
        if(strcmp(s,"LENGTH")==0)
        {
            printf("%d\n",end-begin);
        }
        if(strcmp(s,"LEAVE")==0)
        {
            for(i=begin+x;i<=end-1;i++)
                a[i-1]=a[i];        //中間的人離隊,從後往前覆蓋
            end--;                  //end前移
        }
    }
    return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章