atcoder#AGC045E. [AGC045E] Fragile Balls

[AGC045E] Fragile Balls

Score : 12001200 points

Problem Statement

We have NN boxes numbered 11 to NN, and MM balls numbered 11 to MM. Currently, Ball ii is in Box AiA_i.

You can do the following operation:

  • Choose a box containing two or more balls, pick up one of the balls from that box, and put it into another box.

Since the balls are very easy to break, you cannot move Ball ii more than CiC_i times in total. Within this limit, you can do the operation any number of times.

Your objective is to have Ball ii in Box BiB_i for every ii (1iM1 \leq i \leq M). Determine whether this objective is achievable. If it is, also find the minimum number of operations required to achieve it.

Constraints

  • 1N1051 \leq N \leq 10^5
  • 1M1051 \leq M \leq 10^5
  • 1Ai,BiN1 \leq A_i,B_i \leq N
  • 1Ci1051 \leq C_i \leq 10^5
  • In the situation where the objective is achieved, every box contains one or more balls. That is, for every ii (1iN1 \leq i \leq N), there exists jj such that Bj=iB_j=i.

Input

Input is given from Standard Input in the following format:

NN MM

A1A_1 B1B_1 C1C_1

A2A_2 B2B_2 C2C_2

\vdots

AMA_M BMB_M CMC_M

Output

If the objective is unachievable, print 1-1; if it is achievable, print the minimum number of operations required to achieve it.

3 3
1 2 1
2 1 1
1 3 2
3

We can achieve the objective in three operations, as follows:

  • Pick up Ball 11 from Box 11 and put it into Box 22.
  • Pick up Ball 22 from Box 22 and put it into Box 11.
  • Pick up Ball 33 from Box 11 and put it into Box 33.
2 2
1 2 1
2 1 1
-1
5 5
1 2 1
2 1 1
1 3 2
4 5 1
5 4 1
6
1 1
1 1 1
0