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
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
// clang-format off
#include<bits/stdc++.h>
using namespace std;
using LL=long long;
#define FOR(i,l,r) for(auto i=(l);i<=(r);++i)
#define REP(i,n) FOR(i,0,(n)-1)
#define ssize(x) int(x.size())
template<class A,class B>auto&operator<<(ostream&o,pair<A,B>p){return o<<"("<<p.first<<", "<<p.second<<")";}
template<class T>auto operator<<(ostream&o,T x)->decltype(x.end(),o){o<<"{";int i=0;for(auto e:x)o<<(", ")+2*!i++<<e;return o<<"}";}
#ifdef DEBUG
#define debug(X...)cerr<<"["#X"]: ",[](auto...$){((cerr<<$<<"; "),...)<<"\n";}(X)
#else
#define debug(...) {}
#endif
// clang-format on

#include <ext/pb_ds/assoc_container.hpp>
template<typename A, typename B>
using htable_t = __gnu_pbds::gp_hash_table<A, B>;

class ContiSet
{
    set<pair<int, int>> ranges;  // (l, r)
   public:
    void insert(int x);
    void erase(int x);
    bool conti(int l, int r) const;
};

struct Board
{
    // Objects allocation
    int nrows, ncols;
    htable_t<LL, int> htable;
    vector<pair<int, int>> obj_pos;
    vector<int> freed;

    // About squares
    int nsquares = 0;
    vector<bool> obj_square;

    // Diagonals
    vector<map<int, int>> squares_in_diag[2];
    vector<ContiSet> objs_in_diag[2];

    Board(int nrows, int ncols);

    // Object id at given field or -1 if empty
    int getid(int r, int c) const;
    bool isSquare(int id) const { return obj_square[id]; }

    // Squares
    void setSquare(int id);
    void unsetSquare(int id);
    int getStairsLen(int id, int type) const;
    int getPrevSqOnDiag(int r, int c, int type) const;

    // Creates new object id and sets it at given field
    int new_atp(int r, int c);

    // Removes object at given field
    void rem_atp(int r, int c);

    void debug_print();

   protected:
    static const int margin = 4;
    LL hash_pos(int r, int c) const { return 1LL * r * (ncols + margin) + c; }
    int diag_id0(int r, int c) const { return nrows - r + c + margin; }
    int diag_id1(int r, int c) const { return r + c + margin; }
    int id_to_diagid(int id, int type) const;
    int getNextSqOnDiag(int id, int type) const;
    bool checkConti(int from, int to, int type) const;
};

class Solution
{
    int nall = 0, nstairs = 0;
    Board* board;
    set<int> removable;

   public:
    Solution(Board* board);
    void qadd(int r, int c, bool calc_influe = true);
    void qrem(int r, int c);
    int query(bool brute_stairs = false);

   protected:
    int calc_stairs_brutally();
    pair<set<int>, bool> set_of_changing_ids(int r, int c, bool add = true);
};


int
main()
{
    cin.tie(0)->sync_with_stdio(0);
    int nrows, ncols, ninit, nqueries;
    cin >> nrows >> ncols >> ninit >> nqueries;
    Board board(nrows, ncols);
    Solution solution(&board);

    REP (i, ninit) {
        int r, c;
        cin >> r >> c;
        solution.qadd(r, c, false);
    }
    cout << solution.query(true) << "\n";

    REP (q, nqueries) {
        int r, c;
        cin >> r >> c;
        if (board.getid(r, c) == -1)
            solution.qadd(r, c);
        else
            solution.qrem(r, c);
        cout << solution.query() << "\n";
    }
    return 0;
}


/* ========================== Solution ===================================== */

void
Solution::qadd(int r, int c, bool calc_influ)
{
    // Generate set of ids that will be set to squares
    auto [set_to_sq, if_mid_sq] = set_of_changing_ids(r, c, true);

    debug("ADD", r, c, set_to_sq);

    // Remove influence of all stairs that might depend on set_to_sq
    set<pair<int, int>> touched;
    if (calc_influ) {
        for (const auto& id : set_to_sq) {
            const auto& [r, c] = board->obj_pos[id];
            touched.insert({board->getPrevSqOnDiag(r, c, 0), 0});
            touched.insert({board->getPrevSqOnDiag(r, c + 1, 0), 0});
            touched.insert({board->getPrevSqOnDiag(r, c, 1), 1});
            touched.insert({board->getPrevSqOnDiag(r, c - 1, 1), 1});
        }

        // What mid touches
        touched.insert({board->getPrevSqOnDiag(r, c, 0), 0});
        touched.insert({board->getPrevSqOnDiag(r, c + 1, 0), 0});
        touched.insert({board->getPrevSqOnDiag(r, c, 1), 1});
        touched.insert({board->getPrevSqOnDiag(r, c - 1, 1), 1});

        for (const auto& t : touched) {
            if (t.first == -1) continue;
            nstairs -= board->getStairsLen(t.first, t.second);
        }
    }

    // Mark our ids as squares
    auto mid = board->new_atp(r, c);
    if (if_mid_sq) set_to_sq.insert(mid);
    for (const auto& id : set_to_sq) board->setSquare(id);

    // Add back influence of touched
    if (calc_influ) {
        for (const auto& t : touched) {
            if (t.first == -1) continue;
            nstairs += board->getStairsLen(t.first, t.second);
        }
    }

    // Add influence of our new squares
    if (calc_influ) {
        for (const auto& id : set_to_sq)
            nstairs += board->getStairsLen(id, 0) + board->getStairsLen(id, 1);
    }

    board->debug_print();
    nall += 1;
}

void
Solution::qrem(int r, int c)
{
    // Generate set of ids that might be no longer a square due to mid
    auto mid                     = board->getid(r, c);
    auto [will_unset, if_mid_sq] = set_of_changing_ids(r, c, false);

    // Eliminate ids that are secured by squares around
    static const array<pair<int, int>, 12> offsets = {{
      {-2, -2},
      {-2, -1},
      {-2, 0},
      {-2, 1},
      {-1, -2},
      {-1, 1},
      {0, -2},
      {0, 1},
      {1, -2},
      {1, -1},
      {1, 0},
      {1, 1},
    }};
    for (const auto& offset : offsets) {
        int rp = r + offset.first, cp = c + offset.second;
        auto a = board->getid(rp, cp), b = board->getid(rp, cp + 1),
             c = board->getid(rp + 1, cp), d = board->getid(rp + 1, cp + 1);
        if (a == -1 || b == -1 || c == -1 || d == -1) continue;
        will_unset.erase(a), will_unset.erase(b);
        will_unset.erase(c), will_unset.erase(d);
    }

    // Generate set of ids that will be affected due to some ids being unset
    set<pair<int, int>> touched;
    for (const auto& id : will_unset) {
        const auto& [r, c] = board->obj_pos[id];
        touched.insert({board->getPrevSqOnDiag(r, c, 0), 0});
        touched.insert({board->getPrevSqOnDiag(r, c + 1, 0), 0});
        touched.insert({board->getPrevSqOnDiag(r, c, 1), 1});
        touched.insert({board->getPrevSqOnDiag(r, c - 1, 1), 1});
    }
    // and due to mid being removed
    touched.insert({board->getPrevSqOnDiag(r, c, 0), 0});
    touched.insert({board->getPrevSqOnDiag(r, c + 1, 0), 0});
    touched.insert({board->getPrevSqOnDiag(r, c, 1), 1});
    touched.insert({board->getPrevSqOnDiag(r, c - 1, 1), 1});

    // And now remove influence of them
    vector<pair<int, int>> really_touched;
    for (const auto& t : touched) {
        if (t.first == -1 || t.first == mid || will_unset.count(t.first))
            continue;
        really_touched.emplace_back(t);
        nstairs -= board->getStairsLen(t.first, t.second);
    }

    // And also remove influence of those that we will unset
    for (const auto& id : will_unset)
        nstairs -= board->getStairsLen(id, 0) + board->getStairsLen(id, 1);
    if (if_mid_sq)
        nstairs -= board->getStairsLen(mid, 0) + board->getStairsLen(mid, 1);

    // Unset squares and remove mid
    debug("REM", r, c, will_unset);
    for (const auto& id : will_unset) board->unsetSquare(id);
    if (if_mid_sq) board->unsetSquare(mid);
    board->rem_atp(r, c);

    // Bring back influence of touched
    for (const auto& t : really_touched)
        nstairs += board->getStairsLen(t.first, t.second);

    board->debug_print();
    nall -= 1;
}

int
Solution::query(bool brute_stairs)
{
    if (brute_stairs) nstairs = calc_stairs_brutally();
    debug("QUERY", nall, board->nsquares, nstairs);
    return nall - board->nsquares - nstairs;
}

pair<set<int>, bool>
Solution::set_of_changing_ids(int r, int c, bool add)
{
    set<int> idset;
    bool if_mid_sq = false;

    // Get ids of fields around us
    auto left   = board->getid(r, c - 1);
    auto right  = board->getid(r, c + 1);
    auto up     = board->getid(r - 1, c);
    auto down   = board->getid(r + 1, c);
    auto uleft  = board->getid(r - 1, c - 1);
    auto uright = board->getid(r - 1, c + 1);
    auto dleft  = board->getid(r + 1, c - 1);
    auto dright = board->getid(r + 1, c + 1);

    // We create a square with:
    // 1. up left corner
    if (uleft != -1 && up != -1 && left != -1) {
        if_mid_sq = true;
        if (add ^ board->isSquare(uleft)) idset.insert(uleft);
        if (add ^ board->isSquare(up)) idset.insert(up);
        if (add ^ board->isSquare(left)) idset.insert(left);
    }

    // 2. up right corner
    if (uright != -1 && up != -1 && right != -1) {
        if_mid_sq = true;
        if (add ^ board->isSquare(uright)) idset.insert(uright);
        if (add ^ board->isSquare(up)) idset.insert(up);
        if (add ^ board->isSquare(right)) idset.insert(right);
    }

    // 3. down left corner
    if (dleft != -1 && down != -1 && left != -1) {
        if_mid_sq = true;
        if (add ^ board->isSquare(dleft)) idset.insert(dleft);
        if (add ^ board->isSquare(down)) idset.insert(down);
        if (add ^ board->isSquare(left)) idset.insert(left);
    }

    // 4. down right corner
    if (dright != -1 && down != -1 && right != -1) {
        if_mid_sq = true;
        if (add ^ board->isSquare(dright)) idset.insert(dright);
        if (add ^ board->isSquare(down)) idset.insert(down);
        if (add ^ board->isSquare(right)) idset.insert(right);
    }
    return {idset, if_mid_sq};
}

int
Solution::calc_stairs_brutally()
{
    int res = 0;
    set<int> to_skip(board->freed.begin(), board->freed.end());
    REP (id, ssize(board->obj_pos)) {
        if (to_skip.count(id)) continue;
        if (!board->isSquare(id)) continue;
        res += board->getStairsLen(id, 0);
        res += board->getStairsLen(id, 1);
    }
    return res;
}

Solution::Solution(Board* board)
  : board(board) {};


/* ========================== Board ======================================== */


Board::Board(int nrows, int ncols)
  : nrows(nrows)
  , ncols(ncols)
{
    squares_in_diag[0].resize(diag_id0(-2, ncols) + margin);
    squares_in_diag[1].resize(diag_id1(nrows + 2, ncols) + margin);
    objs_in_diag[0].resize(diag_id0(-2, ncols) + margin);
    objs_in_diag[1].resize(diag_id1(nrows + 2, ncols) + margin);
}

int
Board::getid(int r, int c) const
{
    auto it = htable.find(hash_pos(r, c));
    if (it == htable.end()) return -1;
    return it->second;
}

void
Board::setSquare(int id)
{
    obj_square[id]                        = true, ++nsquares;
    const auto& [r, c]                    = obj_pos[id];
    squares_in_diag[0][diag_id0(r, c)][r] = id;
    squares_in_diag[1][diag_id1(r, c)][r] = id;
}

void
Board::unsetSquare(int id)
{
    if (!obj_square[id]) return;
    obj_square[id]     = false, --nsquares;
    const auto& [r, c] = obj_pos[id];
    squares_in_diag[0][diag_id0(r, c)].erase(r);
    squares_in_diag[1][diag_id1(r, c)].erase(r);
}

int
Board::id_to_diagid(int id, int type) const
{
    const auto& [r, c] = obj_pos[id];
    return type == 0 ? diag_id0(r, c) : diag_id1(r, c);
}

int
Board::getNextSqOnDiag(int id, int type) const
{
    const auto& [r, c] = obj_pos[id];
    const auto& diag   = squares_in_diag[type][id_to_diagid(id, type)];
    auto it            = diag.upper_bound(r);
    if (it == diag.end()) return -1;
    return it->second;
}

int
Board::getPrevSqOnDiag(int r, int c, int type) const
{
    const auto& diag
      = squares_in_diag[type][type == 0 ? diag_id0(r, c) : diag_id1(r, c)];
    auto it = diag.lower_bound(r);
    if (it == diag.begin()) return -1;
    return prev(it)->second;
}

bool
Board::checkConti(int from, int to, int type) const
{
    auto fdiagid = id_to_diagid(from, type);
    const auto& diag = objs_in_diag[type][fdiagid];
    return diag.conti(obj_pos[from].first, obj_pos[to].first);
}

int
Board::getStairsLen(int curr, int type) const
{
    auto nxt = getNextSqOnDiag(curr, type);
    if (nxt == -1) return 0;
    if (!checkConti(curr, nxt, type)) return 0;

    // Obtain ids of first objects in stairs
    const auto& [curr_r, curr_c] = obj_pos[curr];
    const auto& [nxt_r, nxt_c]   = obj_pos[nxt];
    auto curr2                   = getid(curr_r + 1, curr_c);
    auto nxt2 = getid(nxt_r, (type == 0 ? nxt_c - 1 : nxt_c + 1));
    if (curr2 == -1 || nxt2 == -1) return 0;
    if (!checkConti(curr2, nxt2, type)) return 0;

    // Calculate len
    int len = (nxt_r - curr_r) * 2 - 1;
    if (isSquare(curr2)) len -= 1;
    if (nxt2 != curr2 && isSquare(nxt2)) len -= 1;
    if (len) debug(curr_r, curr_c, nxt_r, nxt_c, len);
    return len;
}

int
Board::new_atp(int r, int c)
{
    int id = ssize(obj_pos);
    if (!freed.empty()) {
        id = freed.back();
        freed.pop_back();
    } else {
        obj_pos.emplace_back();
        obj_square.emplace_back();
    }
    obj_pos[id]            = {r, c};
    htable[hash_pos(r, c)] = id;

    // Update data
    objs_in_diag[0][diag_id0(r, c)].insert(r);
    objs_in_diag[1][diag_id1(r, c)].insert(r);
    return id;
}

void
Board::rem_atp(int r, int c)
{
    auto it = htable.find(hash_pos(r, c));
    const auto& [key, id] = *it;

    // Update data
    unsetSquare(id);
    objs_in_diag[0][diag_id0(r, c)].erase(r);
    objs_in_diag[1][diag_id1(r, c)].erase(r);

    freed.emplace_back(id);
    htable.erase(key);
}

void
Board::debug_print()
{
#ifdef DEBUG
    vector<string> output(nrows + 1, string(ncols + 1, ' '));
    output[0]    = string(ncols + 1, '_');
    output[0][0] = ' ';
    FOR (r, 1, nrows) output[r][0] = '|';

    set<int> to_skip(freed.begin(), freed.end());
    REP (id, ssize(obj_pos)) {
        if (to_skip.count(id)) continue;
        const auto& [r, c] = obj_pos[id];
        output[r][c]       = (obj_square[id] ? '#' : '+');
    }
    for (const auto& row : output) cerr << row.c_str() << "\n";
#endif
}


/* ========================== ContiSet ===================================== */

void
ContiSet::insert(int x)
{
    pair<int, int> to_insert = {x, x};
    auto after               = ranges.lower_bound({x, 0});

    // Merge with range before
    if (after != ranges.begin() && prev(after)->second + 1 == x) {
        to_insert.first = prev(after)->first;
        ranges.erase(prev(after));
    }

    // Merge with range after
    if (after != ranges.end() && after->first == x + 1) {
        to_insert.second = after->second;
        ranges.erase(after);
    }
    ranges.insert(to_insert);
}

void
ContiSet::erase(int x)
{
    auto it = ranges.lower_bound({x + 1, 0});
    const auto& [l, r] = *(--it);

    // Insert part of range before it
    if (l < x) ranges.insert(it, {l, x - 1});

    // Insert part of range after it
    if (x < r) ranges.insert(next(it), {x + 1, r});

    // Perform erasion
    ranges.erase(it);
}

bool
ContiSet::conti(int l, int r) const
{
    auto lit = ranges.lower_bound({l + 1, 0});
    return lit != ranges.begin() && prev(lit)->first <= l
           && r <= prev(lit)->second;
}