标签:
http://acm.hdu.edu.cn/showproblem.php?pid=5818
1 #include <cstdio> 2 #include <algorithm> 3 #include <cstring> 4 #include <stack> 5 #include <deque> 6 using namespace std; 7 #define N 100010 8 struct node 9 { 10 int val, id; 11 node () {} 12 node(int val, int id) : val(val), id(id) {} 13 }; 14 deque <node> a, b; 15 stack <node> c; 16 /* 17 官方题解: 18 比较简单巧妙的一个做法是引入一个新的栈C, 19 每次合并的时候就把A和B合并到C上,然后把A和B都清空. 20 push还是按正常做,pop注意当遇到要pop的栈为空时, 21 因为题目保证不会对空栈进行pop操作, 22 所以这时应直接改为对C栈进行pop操作. 23 这样做因为保证每个元素最多只在一次合并中被处理到, 24 pop和push操作当然也是每个元素只做一次,所以总复杂度是O(N)的. 25 26 因为在把A和B放到C上的时候要按照时间顺序放置,所以我就只会 27 搞一个deque,放到C里面的时候比较A和B队头的时间,然后小的先进栈C 28 其他的就和栈是一样的。 29 */ 30 31 int main() 32 { 33 int cas = 0; 34 int q; 35 while(scanf("%d", &q), q) { 36 printf("Case #%d:\n", ++cas); 37 while(!a.empty()) a.pop_back(); 38 while(!b.empty()) b.pop_back(); 39 while(!c.empty()) c.pop(); 40 int cnt = 0; 41 char s[6], ch, chh; 42 node n1, n2; 43 int dhh; 44 while(q--) { 45 scanf("%s %c", s, &ch); 46 if(s[1] == ‘u‘) { 47 scanf("%d", &dhh); 48 if(ch == ‘A‘) a.push_back(node(dhh, ++cnt)); 49 else b.push_back(node(dhh, ++cnt)); 50 } else if(s[1] == ‘o‘) { 51 node ans; 52 if(ch == ‘A‘) { 53 if(!a.empty()) { 54 ans = a.back(); 55 a.pop_back(); 56 } else { 57 ans = c.top(); 58 c.pop(); 59 } 60 } else { 61 if(!b.empty()) { 62 ans = b.back(); 63 b.pop_back(); 64 } else { 65 ans = c.top(); 66 c.pop(); 67 } 68 } 69 printf("%d\n", ans.val); 70 } else { 71 scanf("%*c%c", &chh); 72 while(1){ 73 if(a.empty() && b.empty()) break; 74 int t1 = 0x3f3f3f3f, t2 = 0x3f3f3f3f; 75 if(!a.empty()) { 76 n1 = a.front(); 77 t1 = n1.id; 78 } 79 if(!b.empty()) { 80 n2 = b.front(); 81 t2 = n2.id; 82 } 83 if(t1 < t2) { 84 c.push(n1); 85 a.pop_front(); 86 } else { 87 c.push(n2); 88 b.pop_front(); 89 } 90 } 91 } 92 } 93 } 94 return 0; 95 }
HDU 5818:Joint Stacks(stack + deque)
标签:
原文地址:http://www.cnblogs.com/fightfordream/p/5755851.html