PHƯỚC HƯNG OJ · THỬ THÁCH THUẬT TOÁN

#BS0000310. Đưa mảng về toàn số 0 II (Zero Array Transformation II)

HỌC THEO LỘ TRÌNH

Bài tập thuộc lộ trình

1 lộ trình

Đưa mảng về toàn số 0 II (Zero Array Transformation II)

Zero Array Transformation II

Source: LeetCode

Version: Phuoc Hung OJ Extended

Problem Statement

Given a nonnegative array of length n and q operations (lj,rj,vj)(l_j,r_j,v_j), each operation permits independently decreasing each value in the inclusive zero-based interval by any integer from 0 to v_j. Find the shortest prefix of operations that can make the entire array zero, or report failure.

Input

First line: n,q. Second line: n integers aia_i. Next q lines contain lj,rj,vjl_j,r_j,v_j using zero-based indices.

Output

Print the smallest k, or -1 if impossible.

Subtasks

  • Subtask 1 (20 points): 1≤n,q≤301\le n,q\le30; 0≤ai≤1000\le a_i\le100; 0≤lj≤rj<n0\le l_j\le r_j<n; 1≤vj≤51\le v_j\le5.
  • Subtask 2 (30 points): 1≤n,q≤1051\le n,q\le10^5; 0≤ai≤5⋅1050\le a_i\le5\cdot10^5; 0≤lj≤rj<n0\le l_j\le r_j<n; 1≤vj≤51\le v_j\le5; lj=rjl_j=r_j.
  • Subtask 3 (50 points): 1≤n,q≤1051\le n,q\le10^5; 0≤ai≤5⋅1050\le a_i\le5\cdot10^5; 0≤lj≤rj<n0\le l_j\le r_j<n; 1≤vj≤51\le v_j\le5.

Examples

Input 1

3 3
2 0 2
0 2 1
0 2 1
1 1 3

Output 1

2

Explanation

Decrease both endpoints by one in each of the first two operations. After only the first operation, both endpoints still need one.

Input 2

2 1
0 0
0 1 5

Output 2

0

Explanation

The array is already zero.