Under construction

Still being built. Things may change

I.O.U.

Interview

Time limit3sMemory limit1024 MB

Summary
Given a list of I.O.U. debts between friends, cancel every debt cycle by its minimum amount and output the debts that remain.
Level

Medium5 of 10

Topics
Graph, DFS
Solved
No attempts yet

Problem

You are developing a new app that simplifies expense-sharing among groups of friends. The app lets them record who paid for an expense and how it should be shared with others, using I.O.U.s. For instance, if Alice pays for a meal shared with Bob and Carol, and Bob's and Carol's shares are $5 and $10, respectively, then Bob issues an I.O.U. for $5 to Alice, and Carol issues an I.O.U. for $10 to Alice.

The app keeps a ledger of who owes whom. Cycles can occur. For instance, if Bob initially owes Alice $10 and later pays a $5 expense on behalf of Alice, Alice issues an I.O.U. for $5 to Bob. This I.O.U. cancels out, or reduces, the I.O.U. Alice holds from Bob from $10 to $5. A cycle can also involve more than 2 people.

The app is given a list of issued I.O.U.s. It settles them as much as possible by considering all cycles and reducing each debt in a cycle by the minimum debt in that cycle. After all cycles are considered and canceled, the app outputs who owes whom how much. If cancellation can happen in more than one way, you may choose any of them, as long as no cycles remain at the end. However, you may not create I.O.U.s between friends who never gave an I.O.U. to each other. For example, if Alice owes Bob money and Bob owes the same amount to Carol, you cannot remove Bob and declare that Alice now owes Carol.

Input

The input consists of a single test case. The first line contains two integers nn and mm (1≤n≤1001 \le n \le 100, 0≤m≤10 0000 \le m \le 10\,000), where nn is the number of friends and mm is the number of I.O.U.s issued. Friends are numbered 00 to n−1n-1. The next mm lines each contain three integers aa, bb, cc (0≤a<n0 \le a < n, 0≤b<n0 \le b < n, a≠ba \ne b, 0<c≤1 0000 < c \le 1\,000), meaning friend aa gave friend bb an I.O.U. for cc dollars. Any friend ii holds at most one I.O.U. from any friend jj (i≠ji \ne j), but friend ii may hold an I.O.U. from friend jj while friend jj holds one from ii.

Output

First, output a single number pp, the number of I.O.U.s left after all cycles are canceled. Then output the pp remaining I.O.U.s on the following pp lines, in the same form as the input: three integers aa, bb, cc meaning friend aa owes friend bb cc dollars. Do not output any fully canceled I.O.U.s. Every I.O.U. you output must have c>0c > 0.

Examples3

  1. Example 1

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

    Input
    2 2
    0 1 20
    1 0 5
    
    Expected output
    1
    0 1 15
    
  3. Example 3

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