818D - Multicolored Cars

818D - Multicolored Cars

题意

在 1 到 n 时刻,有 n 量有颜色的车通过,用数字表示颜色,Alice 选择一个颜色A,要求 Bob 选择一个颜色B,使得对于任意时刻 cnt(B) >= cnt(A),即通过的颜色为 B 的车始终不小于颜色为 A 的车。求任意满足条件的解,否则输出 -1 。

分析

举例:

11 4
1 2 3 3 4 1 2 5 4 3 4

以 4 为最右端分段,即1 2 3 3 4为第一段,1 2 5 4第二段,3 4第三段。
用一个集合维护可用的值,数组维护还可用的次数,对于第一段前面的值,直接更新即可,到第二段,1 2出现了,所以仍在集合中,5在前一段中未出现,所以不用考虑,但是3要被加到集合中,因为到第二段,3仍是满足条件的,虽然这一段没有,可以使用前面的3进行抵扣。第三段只出现了一个3,所以3为最终答案。

模拟就好了。

code

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN = 1e6 + 5;
int a[MAXN];
int b[MAXN];
set<int> set1, set2;
int main() {
    ios::sync_with_stdio(0);
    cin.tie(0);
    int n, A;
    cin >> n >> A;
    int f = 0;
    for(int i = 0; i < n; i++) {
        int x;
        cin >> x;
        if(x != A) {
            if(!f || set2.count(x)) {
                set1.insert(x);
                a[x]++;
            }
        } else {
            f = 1;
            int cnt = 0;
            for(auto it : set2) {
                a[it]--;
                if(a[it] == 0) b[cnt++] = it;
            }
            for(int j = 0; j < cnt; j++) set2.erase(b[j]);
            set2.insert(set1.begin(), set1.end());
            set1.clear();
        }
    }
    if(f) {
        if(set2.empty()) cout << "-1" << endl;
        else cout << *set2.begin() << endl;
    }
    else {
        cout << 1001 << endl;
    }
    return 0;
}
posted @ 2017-07-08 22:57  ftae  阅读(294)  评论(0编辑  收藏  举报