Under construction

Still being built. Things may change

Going Dutch

Time limit2sMemory limit512 MB

Summary
Given each person's net balance from the receipts, find the minimum number of money transfers that settles everyone to zero.
Level

Medium7 of 10

Topics
Dynamic programming, Bit manipulation, Backtracking, Greedy
Solved
No attempts yet

Problem

You and your friends have just returned from a vacation in the mountains of the Netherlands. Splitting the bill on every expense during the trip is annoying, so you kept all the receipts instead and wrote down who paid how much for whom. Now it is time to settle the bill.

Each of you could take the receipts showing that someone paid something for you and pay that person back. That takes a lot of transactions, and you want to keep up the lazy spirit from the trip. It does not matter who transfers money to whom, as long as everyone's balance is 00 in the end.

Find the least number of transactions needed to settle the score. One transaction moves money from one person to one other person, and assume everyone has enough spare cash to transfer any amount.

Input

The first line contains two integers MM, the number of people in the group, and NN, the number of receipts from the trip, with 1≤M≤201 \le M \le 20 and 0≤N≤10000 \le N \le 1000.

Each of the next NN lines contains three integers aa, bb, pp with 0≤a,b<M0 \le a, b < M and 1≤p≤10001 \le p \le 1000, a receipt showing that person aa paid pp euros for person bb.

Output

Print a single integer on one line, the least number of transactions necessary to settle all bills.

Examples3

  1. Example 1

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

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

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