USACO 2013 US Open, Gold Problem 1. Photo

USACO 2013 US Open, Gold Problem 1. Photo

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
#include <bits/stdc++.h>
using namespace std;

int N, M;
vector<int> dp;
deque<int> dQ;

signed main() {
    ifstream cin("photo.in");
    ofstream cout("photo.out");

    cin >> N >> M;

    vector<int> lv(N + 2);
    vector<int> rv(N + 2);
    iota(rv.begin(), rv.end(), -1);

    for (int i = 0; i < M; i++) {
        int a, b;
        cin >> a >> b;
        lv[b + 1] = max(lv[b + 1], a);
        rv[b] = min(rv[b], a - 1);
    }

    for (int i = 1; i <= N + 1; i++) {
        lv[i] = max(lv[i], lv[i - 1]);
    }
    for (int i = N; i >= 1; i--) {
        rv[i] = min(rv[i], rv[i + 1]);
    }

    dp.resize(N + 2);

    int p1 = 0;
    int p2 = 0;
    dQ.push_back(0);

    // finding sliding window max using monotonous queue
    for (int i = 1; i <= N + 1; i++) {

        int l = lv[i], r = rv[i];

        // step 1: push in the new values from p2 to r
        while (p2 <= r) {
            // make sure to pop smaller values to keep it a monotonous queue
            while (!dQ.empty() && dp[p2] > dp[dQ.back()]) {
                dQ.pop_back();
            }
            dQ.push_back(p2);
            p2++;
        }

        // step 2: pop the old values from p1 to p2
        // stop if it's empty (previously popped already)
        while (! dQ.empty() && p1 < l) {
            if (dQ.front() == p1) {
                dQ.pop_front();
            }
            p1++;
        }

        // invalid range, so no answer
        if (l > r) {
            dp[i] = -1;
            continue;
        }
        else {
            // also invalid range
            if (dp[dQ.front()] == -1) {
                dp[i] = -1;
            }
            // otherwise, you can add a cow here
            else {
                dp[i] = dp[dQ.front()] + 1;
            }
        }
    }

    // invalid, return -1
    if (dp[N + 1] == -1) {
        cout << -1;
        return 0;
    }
    // since we created new N + 1 cow, we subtract 1 from our total
    cout << dp[N + 1] - 1;

}