CSES - Aalto Competitive Programming 2023 - wk2 - Wed - Old legos
  • Time limit: 1.00 s
  • Memory limit: 512 MB

Uolevi and Maija are visiting their parents. While the blueberry pie is cooking in the oven, they go explore the attic. They find their old legos and decide to build castles from them. There are n legos in a box numbered 1,2,\dots,n, the i-th of which has u_i nostalgic value to Uolevi and m_i to Maija. The siblings then take turns in picking legos from the box and placing them to their castles. Naturally, both try to maximize the value difference between their own castle and their opponents castle.

Formally, the legos will be divided into two sets U and M at the end of the process. Uolevi's castle has value x = \sum_{i \in U}{u_i} and Maija's castle has value y = \sum_{i \in M}{m_i}. Maija tries to minimize x-y while Uolevi tries to maximize it. Calculate x-y if Uolevi gets to pick the first lego and both pick the legos optimally.


First line contain a single integer n.

The 𝑖-th of the next n lines contains two integers u_i and m_𝑖.


Output a single integer x-y.


  • 1 \leq n \leq 10^5
  • 1 \leq u_i, m_i \leq 10^9

Example 1


3 1
9 3
6 3
2 10
1 7




The sequence of picks would be:
Uolevi picks lego 2
Maija picks lego 4
Uolevi picks lego 3
Maija picks lego 5
Uolevi picks lego 1

Example 2


10 2
1 1000