USACO · 1038

Social Distancing

This C++ solution uses binary search for USACO 1038 Social Distancing. Read the reasoning, inspect the code, or try your own test case below.

1038Sorting & searchingBinary searchC++45 lines
Solution195of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Binary search

Social Distancing matches cow placement in disjoint intervals and binary search for the largest minimum distance.

Sorting & searching

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

P_1_Social_Distancing.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    bool good(long long d, int n, vector<pair<long long, long long>>& seg){
        long long cows = 0;
            long long last = 0;
            bool has_last = 0;
            for (auto &p : seg) {
                long long a = p.first, b = p.second;
                long long start;
                if (!has_last) {
                    start = a;
                } else {
                    start = max(a, last + d);
                }
                if (start > b) continue;
                long long diff = b - start;
                long long cnt = 1 + diff / d;
                cows += cnt;
                if (cows >= n) return true;
                long long new_last = start + (cnt - 1) * d;
                last = new_last;
                has_last = true;
            }
            return cows >= n;
    }
    int main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int n, m; cin >> n >> m;
        vector<pair<long long, long long>> seg(m);
        for (int i = 0; i < m; i++) {
            long long a, b; cin >> a >> b;
            seg[i] = {a, b};
        }
        sort(seg.begin(), seg.end());
        long long lo = 1;
        long long hi = 1e18;
        while (lo < hi) {
            long long mid = lo + (hi - lo + 1) / 2;
            if (good(mid, n, seg)) lo = mid;
            else hi = mid - 1;
        }
        cout << lo << "\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.