18.12.16 DSA 双队列

描述

系统A用来维护客户。每个客户的id用一个正整数K来表示,当客户进入系统时用P来表示此用户的优先度。这个系统有以下请求

0

系统停止运行

K P

优先度为P的客户K进入系统

2

找到优先度最高的客户,然后此客户离开系统

3

找到优先度最低的客户,然后此客户离开系统

 

 

输入

每行包括一个请求,最后一行包括一个停止请求(代码0)。对于添加客户请求(代码1),优先度都是唯一的。客户的表示K小于106,优先度P小于107,一个客户可能会被添加多次,每次的优先度可能不同。输出对于每个请求2和3,程序必须输出一行。这行包括此请求中找到客户的id。如果系统中没有客户,输出0

样例输入

2
1 20 14
1 30 3
2
1 10 99
3
2
2
0

样例输出

0
20
30
10
0
 1 #include <iostream>
 2 #include <string.h>
 3 #include <algorithm>
 4 #include <stack>
 5 #include <string>
 6 #include <math.h>
 7 #include <queue>
 8 #include <stdio.h>
 9 #include <string.h>
10 #include <vector>
11 #include <fstream>
12 #define maxn 100005
13 #define inf 999999
14 #define cha 127
15 using namespace std;
16 
17 struct node {
18     int id, p;
19     node(int a, int b) {
20         id = a, p = b;
21     }
22 };
23 deque<node>all;
24 
25 void insert(int id,int p) {
26     all.push_front(node(id, p));
27     int size = all.size(), i=0;
28     for (i = 1; i < size; i++) {
29         if (all[i].p <= p)
30             all[i-1] = all[i];
31         else break;
32     }
33     all[i-1] = node(id, p);
34 }
35 
36 void init() {
37     int cmd;
38     while (scanf("%d", &cmd) && cmd) {
39         if (cmd == 2) {
40             if (!all.empty()) {
41                 printf("%d\n", all.back().id);
42                 all.pop_back();
43             }
44             else
45                 printf("0\n");
46         }
47         else if(cmd==3) {
48             if (!all.empty()) {
49                 printf("%d\n", all.front().id);
50                 all.pop_front();
51             }
52             else
53                 printf("0\n");
54         }
55         else if (cmd == 1) {
56             int k, p;
57             scanf("%d%d", &k, &p);
58             insert(k, p);
59         }
60     }
61 }
62 
63 int main()
64 {
65     init();
66     return 0;
67 }
View Code

看到大家都1ms过就立刻用了线性时间算法

猜你喜欢

转载自www.cnblogs.com/yalphait/p/10127306.html
dsa
今日推荐