Under construction

Still being built. Things may change

Arranging Tickets

Time limit4sMemory limit256 MB

Summary
Given N stations on a circular railway and M travel requests with passenger counts, find the minimum number of ticket packages needed to serve all requests.
Level

Hard9 of 10

Topics
Prefix sum, Binary search, Greedy
Solved
No attempts yet

Problem

Republic of JOI has NN stations numbered from 1 to NN. They are placed in order along a circular railway, clockwise.

There are NN types of train tickets, numbered from 1 to NN. One ticket of type ii (1≤i≤N−11 \le i \le N-1) lets one person travel from station ii to station i+1i+1, or from station i+1i+1 to station ii. One ticket of type NN lets one person travel from station 1 to station NN, or from station NN to station 1. Tickets can only be bought as a package of NN tickets, with one ticket of each type.

You work at a travel agency in Republic of JOI, and your job is to arrange tickets for customers. Today you have MM requests. The ii-th request says that CiC_i people want to travel from station AiA_i to station BiB_i. These CiC_i people do not need to take the same route.

Find the minimum number of ticket packages you need to buy to handle all requests.

Input

The first line contains two space-separated integers NN and MM, the number of stations and the number of requests.

Each of the next MM lines contains three space-separated integers AiA_i, BiB_i, and CiC_i. This means CiC_i people want to travel from station AiA_i to station BiB_i.

Output

Print one line containing the minimum number of ticket packages needed to handle all requests.

Constraints

  • 3≤N≤2000003 \le N \le 200000
  • 1≤M≤1000001 \le M \le 100000
  • 1≤Ai≤N1 \le A_i \le N (1≤i≤M1 \le i \le M)
  • 1≤Bi≤N1 \le B_i \le N (1≤i≤M1 \le i \le M)
  • 1≤Ci≤10000000001 \le C_i \le 1000000000 (1≤i≤M1 \le i \le M)
  • Ai≠BiA_i \ne B_i (1≤i≤M1 \le i \le M)

Examples3

  1. Example 1

    Input
    3 3
    1 2 1
    2 3 1
    3 1 1
    
    Expected output
    1
    
  2. Example 2

    Input
    3 2
    1 2 4
    1 2 2
    
    Expected output
    3
    
  3. Example 3

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