首页 > ACM题库 > HDU-杭电 > HDU 1387 Team Queue-模拟-[解题报告] C++
2013
12-09

HDU 1387 Team Queue-模拟-[解题报告] C++

Team Queue

问题描述 :

Queues and Priority Queues are data structures which are known to most computer scientists. The Team Queue, however, is not so well known, though it occurs often in everyday life. At lunch time the queue in front of the Mensa is a team queue, for example.
In a team queue each element belongs to a team. If an element enters the queue, it first searches the queue from head to tail to check if some of its teammates (elements of the same team) are already in the queue. If yes, it enters the queue right behind them. If not, it enters the queue at the tail and becomes the new last element (bad luck). Dequeuing is done like in normal queues: elements are processed from head to tail in the order they appear in the team queue.

Your task is to write a program that simulates such a team queue.

输入:

The input will contain one or more test cases. Each test case begins with the number of teams t (1<=t<=1000). Then t team descriptions follow, each one consisting of the number of elements belonging to the team and the elements themselves. Elements are integers in the range 0 – 999999. A team may consist of up to 1000 elements.

Finally, a list of commands follows. There are three different kinds of commands:

ENQUEUE x – enter element x into the team queue
DEQUEUE – process the first element and remove it from the queue
STOP – end of test case
The input will be terminated by a value of 0 for t.

输出:

For each test case, first print a line saying "Scenario #k", where k is the number of the test case. Then, for each DEQUEUE command, print the element which is dequeued on a single line. Print a blank line after each test case, even after the last one.

样例输入:

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

样例输出:

Scenario #1
101
102
103
201
202
203

Scenario #2
259001
259002
259003
259004
259005
260001

这个题目的意思很简单 但是如果照着模拟一定会TLE 所以在模拟上也需要很大的技巧

 

先前我使用了并查集来表示团的关系 但后来发先直接使用hash映射就好了 所以不必想这么复杂 而后就是对于队列的模拟

 

由于牵涉到的是插入和删除操作 所以应该使用链表结构 比如stl中的list容器 如果单纯使用该结构一定会超时 所以必须进行优化

 

使用桶结构 将每个队伍看做是一个桶 然后按先来后到的顺序进表 若成员在表中 则定位到该队伍的链表内将其插入 否则插入末尾 并创建队伍链

 

而且这也是我碰到第一个使用了指针优化的题目 用指针数组定位各个队伍的链表地址 以实现快速访问 感觉数据结构对于模拟题来说也是很有用的

 

以下附上代码

 

 

解题报告转自:http://www.cnblogs.com/zhuangli/archive/2008/09/02/1281914.html


  1. 很高兴你会喜欢这个网站。目前还没有一个开发团队,网站是我一个人在维护,都是用的开源系统,也没有太多需要开发的部分,主要是内容整理。非常感谢你的关注。