Simulate with two stacks and save a timestamp for each point. The time stamp of the merge is recorded at each merge mcnt and the Topa and TOPB at this time do TA, TB.
Every time the pop, if the stack top timestamp is greater than mcnt, then normal pop, or in two stacks TA and TB under the maximum time stamp and not yet pop off. Then use the bj[time stamp] to mark the pop already.
#include <cstdio> #include <cstring> #define N 100005using namespace Std;struct node{int id,v;} A[n],b[n];int Bj[n],n,topa,topb,cnt,ele,ta,tb,mcnt,cas;char op[50],st;void Popc () {while (bj[a[ta].id]) ta--;while ( Bj[b[tb].id]) tb--;if (a[ta].id>b[tb].id) {printf ("%d\n", a[ta].v); bj[a[ta].id]=1;} else {printf ("%d\n", b[tb].v); bj[b[tb].id]=1;}} int main () {while (~SCANF ("%d", &n) &&n) {printf ("Case #%d:\n", ++cas); Topa=topb=cnt=mcnt=0;memset (bj,0, sizeof BJ); for (int i=1;i<=n;i++) {scanf ("%s%c", op,&st), if (op[1]== ' u ') {scanf ("%d", &ele), if (st== ' A ') a[++ Topa]= (node) {++cnt,ele};elseb[++topb]= (node) {++cnt,ele};} else if (op[1]== ' O ') {if (st== ' A ') {if (a[topa].id>mcnt) {printf ("%d\n", a[topa].v); bj[a[topa].id]=1;topa--;} Elsepopc ();} Else{if (b[topb].id>mcnt) {printf ("%d\n", b[topb].v); bj[b[topb].id]=1;topb--;} Elsepopc ();}} else if (op[1]== ' E ') {scanf ("%c", &st); MCNT=CNT;TA=TOPA;TB=TOPB;}}} return 0;}
WA has several hair, the result is "if (a[topa].id>mcnt)" Write is >=, why equal not, because POPC function is not top--, so the next top value may have pop off. that if in Popc inside top--, also not, because pop stack a TA, may in pop stack B, so to pa--the words are wrong. This problem is also very convenient with the priority queue.
"HDU more than 5,818 schools" Joint Stacks