Explanation
Let's start with the brute force solution.
We can iterate over all from along with all pairs of intervals and . For each combination, we increment our answer if . This runs in , which is extremely slow.
Consider the two following optimizations:
Optimization 1
Instead of considering each individual , we can think of it as a pair of intervals contributing to all from to . To count this efficiently, we can use difference arrays, where we do range updates by incrementing position by one and decrementing position by one. This improves the time complexity to .
Optimization 2
We should probably take advantage of the fact that is relatively small. Instead of looping through all pairs of left endpoints and right endpoints in time, we can iterate over all distinct left endpoint and right endpoint pairs to process multiple at once in . We can then multiply the frequencies of each pair of values and each pair of values to count how many times and occur among all interval pairs.
Implementation
Time Complexity:
C++
#include <bits/stdc++.h>using namespace std;int main() {int n, m;cin >> n >> m;vector<pair<int, int>> intervals(n);for (auto &interval : intervals) { cin >> interval.first >> interval.second; }
Java
import java.io.*;import java.util.StringTokenizer;public class ConvolutedIntervals {public static void main(String[] args) throws IOException {BufferedReader in = new BufferedReader(new InputStreamReader(System.in));StringTokenizer tokenizer = new StringTokenizer(in.readLine());int n = Integer.parseInt(tokenizer.nextToken());int m = Integer.parseInt(tokenizer.nextToken());
Join the USACO Forum!
Stuck on a problem, or don't understand a module? Join the USACO Forum and get help from other competitive programmers!