USACO · 1160

Convoluted Intervals

This C++ solution uses sweep line for USACO 1160 Convoluted Intervals. Read the reasoning, inspect the code, or try your own test case below.

1160Implementation & simulationSweep lineC++22 lines
Solution054of 248
Open official problem ↗ Download C++ file ↓ Search the library → Open full Code Lab ↗ Report an issue ↗

Approach

Sweep line

Convoluted Intervals asks for counts of ordered interval pairs covering each possible point; the code performs endpoint convolutions and a difference sweep.

Implementation & simulation

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

convoluted_intervals.cpp

C++

    #include <bits/stdc++.h>
    using namespace std;
    #define int long long
    int l[5001], r[5001], psa[5001 * 2];
    signed main(){
        ios::sync_with_stdio(0); cin.tie(0);
        int n, m; cin >> n >> m;
        for(int i = 0; i < n; i++){int a, b; cin >> a >> b; l[a]++; r[b]++;}
        int k = 2 * m;
        for(int i = 0; i <= m; i++){
            for(int j = 0; j <= m; j++){
                psa[i + j] += l[i] * l[j];
                psa[i + j + 1] -= r[i] * r[j];
            } 
        }
        cout << psa[0] << '\n';
        for(int i = 1; i <= k; i++){
            psa[i] = psa[i] + psa[i - 1];
            cout << psa[i] << '\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.