Under construction

Still being built. Things may change

Aboard the Bus to the Workshop, Hello

Time limit1sMemory limit1024 MB

Summary
Given a 3-row by N-column bus with staff seats in rows 1 and 3, find the fewest air conditioners to turn on so every cell is cooled, or -1 if impossible.
Level

Medium6 of 10

Topics
Dynamic programming, Greedy
Solved
No attempts yet

Problem

Staff of 월간 향유회 are riding a bus shaped like a rectangle with 33 rows and NN columns to a workshop. Each cell in rows 11 and 33 has a seat and an air conditioner. Turning on the air conditioner in a cell cools that cell and every cell that shares a side with it. There are MM staff members in total, and each one sits in a seat on the bus and decides whether to turn on the air conditioner in that cell. All staff sit in different seats.

You manage the bus's air conditioning system and may turn on the air conditioners in seats that no staff member occupies. To keep the bus comfortable, you want every cell, including those in row 22, to be cooled. Find the minimum number of air conditioners that must be turned on to cool every cell of the bus. Air conditioners turned on by staff members count toward this number too.

Input

The first line contains the number of columns NN and the number of staff members MM, separated by a space. (1≤M≤2×N≤400 000)(1 \le M \le 2 \times N \le 400\,000)

The next MM lines each contain xix_i, yiy_i, and tit_i, separated by spaces. Staff member ii sits in cell (xi,yi)(x_i, y_i). If ti=1t_i = 1, that staff member turns on the air conditioner in that cell. If ti=0t_i = 0, it stays off. (xi∈{1,3}; 1≤yi≤N; ti∈{0,1})(x_i \in \{1, 3\};\ 1 \le y_i \le N;\ t_i \in \{0, 1\})

All staff sit in different seats, and all input values are integers.

Output

Print the minimum number of air conditioners that must be turned on to cool every cell of the bus. If no way of turning them on cools every cell, print -1 instead.

Examples2

  1. Example 1

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

    Input
    1 2
    1 1 0
    3 1 0
    
    Expected output
    -1