Cod sursa(job #858765)

Utilizator toranagahVlad Badelita toranagah Data 19 ianuarie 2013 12:48:38
Problema Secventa 5 Scor 0
Compilator cpp Status done
Runda Arhiva de probleme Marime 2.04 kb
#include <deque>
#include <iostream>
#include <map>
using namespace std;
#define FORIT(it, v) for (typeof((v).begin()) it = (v).begin(); it != (v).end(); ++it)
const int MAX_N = (1 << 21) + 10;
typedef map<int, int>::iterator mit;
typedef unsigned long long uint64;

int N, L, U;
int sir[MAX_N];

uint64 compute_subsets(int*, int);
void debug(map<int, int>&, deque<int>&);
int main() {
    cin >> N >> L >> U;
    for (int i = 1; i <= N; ++i) {
        cin >> sir[i];
    }
    cout << compute_subsets(sir, U) - compute_subsets(sir, L - 1);
}

uint64 compute_subsets(int* v, int limit) {
    if (limit == 0) return 0;
    uint64 result = 0;
    deque<int> dq;
    map<int, int> hash;
    int numValues = 0;
    for (int i = 1; i <= N; ++i) {
        dq.push_back(v[i]);
        int valBack = dq.back();
        mit itBack = hash.find(valBack);
        if (itBack == hash.end()) {
            ++numValues;
            if (numValues > limit) {
                int valFront = dq.front();
                mit itFront = hash.find(valFront);
                while (itFront->second > 0 && !dq.empty()) {
                    --itFront->second;
                    dq.pop_front();
                    if (itFront->second > 0 && dq.front() != valFront) {
                        valFront = dq.front();
                        itFront = hash.find(valFront);
                    }
                }
                if (itFront == hash.end()) {
                    cerr << "INVALID MALLOC" << endl;
                    cerr << valFront << endl;
                    debug(hash, dq);
                }
                hash.erase(itFront);
                --numValues;
            }
            hash.insert(make_pair(valBack, 1));
        } else {
            ++itBack->second;
        }
        result += dq.size();
    }
    return result;
}

void debug(map<int, int>& h, deque<int>& d) {
    cerr << "ZE map: \n";
    FORIT (it, h) {
        cerr << it->first << ' ' << it->second << endl;
    }
    cerr << "ZE deq: \n";
    FORIT (it, d) {
        cerr << *it << endl;
    }
    cerr << endl;
}