Question link:
Http://uva.onlinejudge.org/index.php? Option = com_onlinejudge & Itemid = 8 & page = show_problem & category = & problem = 481 & mosmsg = Submission + received + with + ID + 11144937
Question meaning:
Give you n groups and members of each group, let you create a queue, the start queue is empty.
There are two operations:
1. enqueue X: If no group Friends of X exist in the queue, insert X to the end of the queue. If yes, insert it to the end of the last element of the group.
2. dequeue.
Solution:
The key to the problem is how to quickly locate the Insert Location. Analysis shows that if the queue has a group of friends, it will only be inserted to the last position of the group. If not, it will be inserted to the last position of the queue.
So we can think of using last [I] To save the iterator of the last element of each group, and using team [I] to represent the queue to which I belongs.
Code:
# Include <iostream> # include <cmath> # include <cstdio> # include <cstdlib> # include <string> # include <cstring> # include <algorithm> # include <vector> # include <map> # include <stack> # include <queue> # include <list> # define EPS 1e-6 # define Inf (1 <20) # define PI ACOs (-1.0) using namespace STD; int team [1000000]; int main () {int N, Ca (0); int temp, cur; char order [20]; while (scanf ("% d", & N )! = EOF & N) {for (INT I = 1; I <= N; I ++) {scanf ("% d", & temp ); for (Int J = 1; j <= temp; j ++) {scanf ("% d", & cur); team [cur] = I; // queue to which the element belongs} List <int> mylist, templist; // templist is only used as a constant to mark the ending list <int >:: iterator last [1010]; for (INT I = 1; I <= N; I ++) Last [I] = templist. end (); // start each group with zero elements in the queue printf ("Scenario # % d \ n", ++ CA); While (scanf ("% s ", order) & strcmp (Order, "stop") {If (strcmp (Order, "enqueue") = 0) {scanf ("% d", & cur ); if (last [Team [cur] = templist. end () // If the queue does not contain the Member's last [Team [cur] = mylist. insert (mylist. end (), cur); // insert this element to the final else of the queue {last [Team [cur] ++; // if the last [Team [cur] = mylist is in the queue. insert (last [Team [cur], cur); // insert to the end of the last element of the group} else {cur = mylist. front (); printf ("% d \ n", cur); List <int >:: iterator tt; TT = mylist. begin (); If (TT = last [Team [cur]) // check whether the element is the last one, otherwise, you need to change the value of last [Team [cur] = templist. end (); mylist. pop_front () ;}} putchar ('\ n ');}}