codefoce Cooking Time

 1 #include <bits/stdc++.h> 
 2 using namespace std;
 3 struct T {  // 贪心 优先弹出相邻靠后的材料
 4     int id;
 5     int p;
 6     bool  operator < (const T& t) const {
 7         return p < t.p;
 8     }
 9 };
10 const int N = 1e5 + 7;
11 const int inf = 0x3f3f3f3f;
12 int a[N], sort_a[N], num;
13 bool isok[N];
14 int pre[N];
15 int p[N];
16 int n, k;
17 priority_queue<T> q;
18 inline int f (int x) {
19     return lower_bound(sort_a + 1, sort_a + 1 + num, x) - sort_a; // 错误一 离散化后是num
20 }
21 int main ()
22 {
23     int w; scanf ("%d",&w);
24     while (w--) {
25         while (!q.empty()) q.pop();
26         memset (isok, 0, sizeof(isok));
27         scanf ("%d %d",&n,&k);
28         for (int i = 1; i <= n; i++)  {
29             scanf ("%d", &a[i]);
30             sort_a[i] = a[i];
31         }
32         sort (sort_a + 1, sort_a + 1 + n);
33         num = 1;
34         for (int i = 2; i <= n; i++) {
35             if (sort_a[i] != sort_a[num])
36                 sort_a[++num] = sort_a[i];
37         }
38         int sum = 0; int t = 0;
39         for (int i = 1; i <= num; i++)
40             pre[i] = inf;
41         for (int i = n; i >= 1; i--) {
42             int x = f(a[i]);// pre[i]  元素i最最近出现的位置 
43             p[i] = pre[x];// p[i] a[i] 与a[i]相同元素相邻位置
44             pre[x] = i;
45         }
46         for (int i = 1; i <= n; i++) {
47             int x = f(a[i]);
48             if (!isok[x]) {
49                 sum++;
50                 if (t < k) {
51                     T temp = {x, p[i]};
52                     q.push(temp);  isok[x] = 1;
53                     t++;
54                 }
55                 else {
56                     T t1 = q.top(); q.pop(); isok[t1.id] = 0; 
57                     T temp = {x, p[i]};
58                     q.push(temp);  isok[x] = 1;
59                 }
60             }
61             else {// 错误二: 即使原来在内存中也要去更新它的位置
62                 T temp= {x,p[i]};
63                 q.push(temp);
64             }
65         }
66         printf ("%d
", sum);
67 }
68 return 0;
69 }

链接 : http://codeforces.com/gym/101498/problem/F

抓住青春的尾巴。。。
原文地址:https://www.cnblogs.com/xidian-mao/p/8966894.html