Bubble Sort

시간 제한2초메모리 제한1024 MB

요약
배열의 여러 구간 최솟값 조건이 주어질 때, 가능한 배열 중 버블 정렬 교환 횟수의 최솟값을 구하거나 불가능을 판정한다.
난이도

어려움10점 중 8점

유형
그리디, 정렬, 이분 탐색, 구현
정답자
아직 제출이 없습니다

문제

Recently, little Z has developed a strong interest in bubble sorting.

Here is the pseudocode for bubble sort:

Input: a sequence a[1...n] of length n
Output: a result sorted from small to large
  for i = 1 to n do:
    for j = 1 to n - 1 do
      if (a[j] > a[j + 1])
          Swap the values of a[j] and a[j + 1]

The number of swaps in bubble sort is defined as the number of swaps performed during sorting, which is the number of times the sixth line of the above bubble sort pseudocode is executed. He wants to find a sequence with as few exchanges as possible.

The sequences studied by little Z consists of non-negative integers. It is of length nn and must satisfy mm additional conditions.

The ii-th condition is: the minimum of the numbers with indices in \[L\[i],R\[i]]\[L\[i], R\[i]], namely a\[L\[i]],a\[L\[i]+1],…,a\[R\[i]]a\[L\[i]], a\[L\[i]+1],\ldots, a\[R\[i]], is exactly V\[i]V\[i].

He knows that bubble sort often times out. So, he wants to know what is the minimum number of swaps for bubble sort among all sequences that satisfy the additional condition.

입력

There are multiple sets of data in this question.

The first line of input contains a positive integer TT.

For each set of data, the first row contains two positive integers n, m. Data guarantees 1≤n,m≤1061 \leq n, m \leq 10^6.

The next m lines, each with three non-negative integers L\[i],R\[i],V\[i]L\[i], R\[i], V\[i], represent a set of additional conditions. Data guarantees 1≤L\[i]≤R\[i]≤n,0≤V\[i]≤1091 \leq L\[i] \leq R\[i] \leq n, 0 \leq V\[i] \leq 10^9.

출력

The output is TT lines in total, one integer per line.

For each set of data, if there are sequences that satisfy the m additional conditions, output the minimum number of exchanges in bubble sort among all the sequences that satisfy the additional conditions. If there is no sequence satisfying all conditions, output −1-1.

제한

All test points satisfy: 1≤T≤10001 \leq T \leq 1000, 1≤∑n,∑m≤1061 \leq \sum n,\sum m \leq 10^{6}, 1≤L\[i]≤R\[i]≤n1 \leq L\[i] \leq R\[i] \leq n, 0≤V\[i]≤1090 \leq V\[i] \leq 10^9, ∑n,∑m≤106\sum n, \sum m \leq 10^6 where ∑n,∑m\sum n, \sum m represent the sum of nn and mm of all test points, respectively.

힌트

Some of the test points in this question have a large amount of input. We recommend that you use the fast I/O.

예제1

  1. 예제 1

    입력
    1
    3 2
    1 1 2022
    2 3 39
    
    예상 출력
    1