cppAcademy
FROM LEARNING TO COMPETING

Expert.
Put your skills to the test.

Bulgarian Informatics Group A · 2009–2026

217 independently explained problems: 54 Municipal, 54 Regional and 109 National. Start with the easier tasks and work upwards. Difficulty labels are learning estimates, not official ratings; Group A also includes challenging national-level problems. The 109 National-round tasks shared by Groups A and B retain their existing permanent URLs and explanations. Years follow Arena’s competition-season labels. Source clarifications and special grader requirements are noted on affected tasks.
GROUP A2009 · EasyDifference arrays

Coloring

National Olympiad — Municipal round (2009 season)

Submission name: color.cpp

Problem summary

Integer points 1 through 500000 start white. Toggle every point of each inclusive interval. Find the longest final run of consecutive black points.

Input

N, followed by N pairs a b.

Output

The longest black run length, or zero if there are no black points.

Constraints

1 ≤ N ≤ 5000; 1 ≤ a ≤ b ≤ 500000.

Worked example

Official statement example.

Input

2
3 7
5 10

Output

3

Solution analysis

  1. An interval toggle changes parity at its left endpoint and immediately after its right endpoint. Record these changes with XOR in a difference array.
  2. Scan coordinates from 1 through 500000, maintaining the XOR prefix. A parity of one means black: extend the current run; otherwise reset it. Track its maximum.
  3. For [3,7] and [5,10], overlap points 5 through 7 are toggled twice and return to white. The black runs are [3,4] and [8,10], with lengths 2 and 3.

Why it works

At coordinate x the XOR prefix contains one contribution for exactly those intervals covering x, so it equals the final color. The scan measures every maximal black run and therefore reports the longest.

Complexity: O(N+500000) time and O(500000) space.

Watch out. Toggle at b+1, not at b.,Repeated intervals cancel.

Commented C++17 solution

An independently written complete program with standard headers.

// Key idea: At coordinate x the XOR prefix contains one contribution for exactly those intervals
// covering x, so it equals the final color. The scan measures every maximal black run and therefore
// reports the longest.
#include<algorithm>
#include<iostream>
#include<vector>
using namespace std;
int main(){
    int n;
    cin>>n;
    vector<unsigned char>delta(500002,0);
    while(n--){
        int a,b;
        cin>>a>>b;
        delta[a]^=1;
        delta[b+1]^=1;
    }
    int parity=0,run=0,answer=0;
    for(int x=1;x<=500000;++x){
        parity^=delta[x];
        run=parity?run+1:0;
        answer=max(answer,run);
    }
    cout<<answer<<'\n';
}

Source: Arena Olimpiici ↗