算法 团体队列 UVa540 及C++STL之队列回顾

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43269048/article/details/99825356

贴上题目链接:UVa540
题目解析:该题目中有两个队列:每个团队有一个队列,而团队整体又形成一个队列。例如,有三个团队编号分别为1,2,3,每个团队的队员集合分别为{101,102,103}、{201,202}、{301、302、303},团队的整体队列为{3,1,2},代码如下:

#include<iostream>
#include<cmath>
#include<cstdio> 
#include<map>
#include<algorithm>
#include<vector>
#include<set>
#include<stack>
#include<queue>
using namespace std;
const int maxt=1010;
int main()
{
    int t,kase=0;
    while(cin>>t &&t){
    	printf("Scenario #%d\n",++kase);
    	
    	//记录所有人的团队编号
		map<int,int> team; //team[x]表示编号为x的人所在的团队
		for(int i=0;i<t;i++){
			int n,x;
			scanf("%d",&n);
			while(n--){
				scanf("%d",&x);
				team[x]=i;
			}
		}
		//模拟
		queue<int> q,q2[maxt];  //q是团队的队列,而q2[i]是团队成员i所在的队列
		for(;;){
			int x;
			char cmd[10];
			scanf("s",cmd);
			if(cmd[0]=='S') break;
			else if(cmd[0]=='D'){
				int t=q.front();
				printf("%d\n",q2[t].front());
				q2[t].pop();
				if(q2[t].empty()) q.pop();//团体t全体出队列 
			}
			else if(cmd[0]=='E'){
				scanf("%d",&x);
				int t=team[x];
				if(q2[t].empty()) q.push(t); //团队t进入队列
				q2[t].push(x); 
			}
		}
		printf("\n");
    }
    return 0;
}

**队列(Queue)**包含在头文件中,队列也是一种运算受限的线性表,两头都有限制,插入只能在表的一端进行(只进不出),而删除只能在表的另一端进行(只出不进),允许删除的一端称为队尾(rear),允许插入的一端称为队头 (Front),如图所示:队列描述
队列的基本操作:
头文件

push(x) 将x压入队列的末端

pop() 弹出队列的第一个元素(队顶元素),注意此函数并不返回任何值

front() 返回第一个元素(队顶元素)

back() 返回最后被压入的元素(队尾元素)

empty() 当队列为空时,返回true

size() 返回队列的长度

猜你喜欢

转载自blog.csdn.net/qq_43269048/article/details/99825356
今日推荐