DMOJ · mockccc15j5

Royal Guard

This C++ solution uses binary search for DMOJ mockccc15j5 Royal Guard. Read the reasoning, inspect the code, or try your own test case below.

mockccc15j5Data structuresBinary searchC++51 lines
Solution179of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Binary search

Royal Guard matches the coordinate data and orthogonal-path range-counting performed by the code.

Data structures

Problem and code

Useful links.

Written by benbenyaojifen. Try the problem first, then compare your approach with the code.

Open official problem ↗View exact source file ↗
Implementation

royal_guard.cpp

C++

    #include <bits/stdc++.h>
     
    using namespace std;
     
    #define int long long 
     
    signed main(){
        ios::sync_with_stdio(0);
        cin.tie(0);
        int n;
        cin >> n;
        unordered_map<int, vector<int>> row, col;
        for(int i = 0; i < n; i++){
            int x, y;
            cin >> x >> y;
            row[y].push_back(x); col[x].push_back(y);
        }  
        for(auto &r : row){
            auto &v = r.second;
            sort(v.begin(), v.end());
        }
        for(auto &c : col){
            auto &v = c.second;
            sort(v.begin(), v.end());
        }
        int m;
        cin >> m;
        int x, y;
        cin >> x >> y;
        int cnt = 0;
        for(int i = 1; i < m; i++){
            int nx, ny;
            cin >> nx >> ny;
            if(x == nx){ 
                int lo = min(ny, y), hi = max(ny, y);
                if(col.count(nx)){
                    const auto &v = col[nx];
                    cnt += upper_bound(v.begin(), v.end(), hi) - lower_bound(v.begin(), v.end(), lo);
                }
            } else { 
                int lo = min(nx, x), hi = max(nx, x);
                if(row.count(ny)){
                    const auto &v = row[ny];
                    cnt += upper_bound(v.begin(), v.end(), hi) - lower_bound(v.begin(), v.end(), lo);
                }
            }
            x = nx; y = ny;
        }
        cout << cnt << '\n';
        return 0;
    }
        

Did this explanation save you time? I'm a Grade 11 student building this free library to make difficult algorithms easier to understand.

Buy me a coffee ↗Keep studying →

Test this problem

Run your code here.

Paste your code, run a test case, compare the output, or trace selected values.

Full trace, comparison & stress testing ↗
StatusReady
Output
No run yet.
Diagnostics
No diagnostics yet.

Each run is isolated and has strict limits. Passing one test does not guarantee the judge will accept the solution.