Under construction

Still being built. Things may change

Barn Allocation

Time limit2sMemory limit128 MB

Summary
Given stall capacities and interval requests, find the maximum number of requests that can be granted without any stall exceeding its capacity.
Level

Hard8 of 10

Topics
Greedy, Segment tree, Sorting, Intervals
Solved
No attempts yet

Problem

Farmer John has opened a new barn and is accepting stall-allocation requests from his cows, since some stalls have a nicer view of the pastures.

The barn has NN stalls numbered 11 through NN (1≤N≤1000001 \le N \le 100000); stall ii can hold at most CiC_i cows at the same time (1≤Ci≤1000001 \le C_i \le 100000). Each cow requests a contiguous interval of stalls [Ai,Bi][A_i, B_i] (1≤Ai≤Bi≤N1 \le A_i \le B_i \le N) in which to roam. To grant such a request, every stall in the range Ai…BiA_i \dots B_i must have spare capacity for that cow the whole time she wanders.

You are given MM requests (1≤M≤1000001 \le M \le 100000). Granting a request makes the cow occupy one unit of capacity in every stall of her interval simultaneously. Determine the maximum number of requests that can be granted at once so that no stall's capacity is ever exceeded.

For example, consider a barn with 55 stalls whose capacities and requests are shown below:

Stall id:    1   2   3   4   5
           +---+---+---+---+---+
Capacity:  | 1 | 3 | 2 | 1 | 3 |
           +---+---+---+---+---+
Cow 1       XXXXXXXXXXX             (1, 3)
Cow 2           XXXXXXXXXXXXXXX     (2, 5)
Cow 3           XXXXXXX             (2, 3)
Cow 4                   XXXXXXX     (4, 5)

All four requests cannot be granted together, because stalls 33 and 44 would exceed their capacity. However, cows 11, 33, and 44 can all be granted at the same time without exceeding any capacity, so the maximum here is 33.

Input

  • Line 1: two space-separated integers NN and MM.
  • Lines 22 to N+1N+1: line i+1i+1 contains one integer CiC_i, the capacity of stall ii.
  • Lines N+2N+2 to N+M+1N+M+1: line i+N+1i+N+1 contains two integers AiA_i and BiB_i, the interval requested by cow ii.

Output

  • A single line containing the maximum number of requests that can be granted.

Examples1

  1. Example 1

    Input
    5 4
    1
    3
    2
    1
    3
    1 3
    2 5
    2 3
    4 5
    
    Expected output
    3