queue 之团队队列(摘)

 有t个团队的人正在排一个长队。每次新来一个人时,如果他有队友在排队,那么这个新人会插队到最后一个队友的身后。如果没有任何一个队友排队,则他会排到长队的队尾。

   输入每个团队中所有队员的编号,要求支持如下3种指令(前两种指令可以穿插进行)

对于每个DEQUEUE指令,输出出队人的编号。

Sample Input

2
3 101 102 103
3 201 202 203
ENQUEUE 101
ENQUEUE 201
ENQUEUE
102
ENQUEUE 202
ENQUEUE 103
ENQUEUE
203
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
STOP
2
5
259001 259002 259003 259004 259005
6 260001 260002 260003 260004 260005
260006
ENQUEUE 259001
ENQUEUE 260001
ENQUEUE 259002
ENQUEUE
259003
ENQUEUE 259004
ENQUEUE 259005
DEQUEUE
DEQUEUE
ENQUEUE
260002
ENQUEUE
260003
DEQUEUE
DEQUEUE
DEQUEUE
DEQUEUE
STOP
0

Sample
Output

Scenario
#1
101
102
103
201
202
203

Scenario
#2
259001
259002
259003
259004
259005
260001

#include<cstdio>
#include<queue>
#include<map>
using namespace std;
const int maxt=1000+10;
int main() 
{
    int t,kase=0;
    while(scanf("%d",&t)==1&&t){          //t为团队个数
        

        //开始记录所有人的团队编号
        map<int,int>team;              //team[x]表示编号为x的人所在的团队编号
        for(int i=0;i<t;i++){
            int n,x;
            scanf("%d",&n);          //n为该团队的人数
            while(n--){
                scanf("%d",&x);      
                team[x]=i; 
            }
        }
        printf("Scenario #%d
",++kase);
        //模拟开始!
        queue<int>q,q2[maxt];          //q是团队的队列,而q2[i]是团队i成员的队列
        while(1){
            int x;
            char cmd[10];
            scanf("%s",cmd);
            if(cmd[0]=='S')break;
            else if(cmd[0]=='D'){
                int t=q.front();                //front()调用容器中第一个元素
                printf("%d
",q2[t].front());   
                q2[t].pop();                    //移除队列首元素
                if(q2[t].empty())q.pop();      //团体t全体出队列
            }
            else if(cmd[0]=='E'){              //编号为x的人进入队伍
                scanf("%d",&x);
                int t=team[x];                //t为编号为x的人所在的团队
                if(q2[t].empty())q.push(t);        //团队t进入队列
                q2[t].push(x);                  //q2[t]为该团队在队伍中的人的队列
            }
        }
        printf("
");
    }
    //system("pause");
    return 0;
}
push()会将一个元素置入queue中。
  • front()会返回queue内的第一个元素(也就是第一个被置入的元素)。
  • back()会返回queue中最后一个元素(也就是最后被插入的元素)。
  • top()取队首元素(但不删除)。
  • pop()会从queue中移除一个元素。
  • 注意:pop()虽然会移除下一个元素,但是并不返回它,front()和back()返回下一个元素但并不移除该元素。

另:

优先队列也定义在头文件<queue>中,用"priority_quene<int> pq"来声明。(越小的整数优先级越低)

由于出队的元素并不是最先进队的元素,出队的方法由front()变为了top().

越小的整数优先级越大的定义方式 "priority_queue<int,vector<int>,greater<int> > pq"

自定义类型也可以组成优先级队列,但必须为每个元素定义一个优先级。

eg.  实现 “个位数的的整数优先级反而小”  ,可以定义一个结构体cmp,重载“()” 运算符,然后用“priority_queue<int,vector<int>,cmp> pq"的方式定义。

下面是cmp的定义

struct cmp{

        bool operator() (const int a, const int b)const{                  //a的优先级比b小时返回true

                return a%10>b%10;

           }

}

原文地址:https://www.cnblogs.com/farewell-farewell/p/5244914.html