Problem:
Problem D: The House of Huge Family

Mr. Dango's family has an extremely huge number of members.
Once it had about 100 members, and now it has as many as population of a city.
It is jokingly guessed that the member might fill this planet in the near future.

Mr. Dango's family, the huge family, is getting their new house.
Scale of the house is as large as that of town.

They all had warm and gracious personality and were close each other.
However, in this year the two members of them became to hate each other.
Since the two members had enormous influence in the family, they were split into two groups.

They hope that the two groups don't meet each other in the new house.
Though they are in the same building, they can avoid to meet each other by adjusting passageways.

Now, you have a figure of room layout. Your task is written below.

You have to decide the two groups each room should belong to.
Besides you must make it impossible that they move from any rooms belonging to one group to any rooms belonging to the other group.
All of the rooms need to belong to exactly one group.
And any group has at least one room.

To do the task, you can cancel building passageway.
Because the house is under construction, to cancel causes some cost.
You'll be given the number of rooms and information of passageway.
You have to do the task by the lowest cost.

Please answer the lowest cost.

By characteristics of Mr. Dango's family, they move very slowly.
So all passageways are escalators.
Because of it, the passageways are one-way.

Input

The input consists of multiple datasets.
Each dataset is given in the following format.

n m
X1 Y1 C1
...
Xm Ym Cm

All numbers in each datasets are integers.
The integers in each line are separated by a space.

The first line of each datasets contains two integers.
n is the number of rooms in the house, m is the number of passageways in the house.
Each room is indexed from 0 to n-1.

Each of following m lines gives the details of the passageways in the house.
Each line contains three integers.
The first integer Xi is an index of the room, the starting point of the passageway.
The second integer Yi is an index of the room, the end point of the passageway.
The third integer Ci is the cost to cancel construction of the passageway.
The passageways, they are escalators, are one-way.
The last dataset is followed by a line containing two zeros (separated by a space).

Constraints

2 ≤ n ≤ 100

-10,000 ≤ Ci ≤ 10,000

Y1 ... Ym can't be duplicated integer by each other.

Output

For each dataset, print the lowest cost in a line. You may assume that the all of integers of both the answers and the input can be represented by 32 bits signed integers.

Sample input

3 2
0 1 2
1 2 1
2 1
0 1 100
2 1
0 1 0
2 1
0 1 -1
0 0

Sample output

1
100
0
-1

Solution in Rust (judge verdict: Accepted)

extern crate core;

use std::fmt;
use std::cmp::{Ordering, min, max};
use std::f32::MAX;
use std::ops::{Add, Sub, Mul, Div, Neg, Index, IndexMut, SubAssign, Range};
use std::collections::{BTreeMap, VecDeque, BinaryHeap, BTreeSet, HashMap};
use std::fmt::{Display, Formatter, Error};
use std::hash::{Hash, Hasher};

fn show<T: Display>(vec: &Vec<T>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        print!("[{}", vec[0]);
        for i in 1 .. vec.len() {
            print!(", {}", vec[i]);
        }
        println!("]");
    }
}
fn show2<T: Display>(vec: &Vec<Vec<T>>) {
    if vec.is_empty() {
        println!("[]");
    }else {
        for l in vec {
            show(l);
        }
    }
}
macro_rules! read_line{
    () => {{
        let mut line = String::new();
        std::io::stdin().read_line(&mut line).ok();
        line
    }};
    (delimiter: ' ') => {
        read_line!().split_whitespace().map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (delimiter: $p:expr) => {
        read_line!().split($p).map(|x|x.to_string()).collect::<Vec<_>>()
    };
    (' ') => {
        read_line!(delimiter: ' ')
    };
    ($delimiter:expr) => {
        read_line!(delimiter: $delimiter)
    };
    (' '; $ty:ty) => {
        read_line!().split_whitespace().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
    ($delimiter:expr; $ty:ty) => {
        read_line!($delimiter).into_iter().map(|x|x.parse::<$ty>().ok().unwrap()).collect::<Vec<$ty>>()
    };
}
macro_rules! read_value{
    () => {
        read_line!().trim().parse().ok().unwrap()
    }
}
macro_rules! let_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}
macro_rules! let_mut_all {
    ($($n:ident:$t:ty),*) => {
        let line = read_line!(delimiter: ' ');
        let mut iter = line.iter();
        $(let mut $n:$t = iter.next().unwrap().parse().ok().unwrap();)*
    };
}
#[derive(Copy, Clone)]
struct Edge {
    to: usize, pair: usize, flow: i32
}
fn bfs(nodes: &Vec<Vec<Edge>>, source: usize, sink: usize, depth: &mut Vec<i32>) {
    for i in 0 .. depth.len() {
        depth[i] = -1;
    }
    let mut queue = VecDeque::new();
    queue.push_back(source);
    depth[source] = 0;
    while let Some(current) = queue.pop_front() {
        if current == sink {
            break
        }
        for &next in &nodes[current] {
            if next.flow > 0 && depth[next.to] == - 1 {
                depth[next.to] = depth[current] + 1;
                queue.push_back(next.to);
            }
        }
    }
}
fn dfs(nodes: &mut Vec<Vec<Edge>>, current: usize, sink: usize, depth: &Vec<i32>, searching: &mut Vec<usize>, min_flow: i32) -> Option<i32> {
    if current == sink {
        Some(min_flow)
    }else {
        while searching[current] < nodes[current].len() {
            let Edge{to: next, pair: pair, flow: flow} = nodes[current][searching[current]];
            if flow > 0 && depth[current] < depth[next] {
                if let Some(pushed_flow) = dfs(nodes, next, sink, depth, searching, min(min_flow, flow)) {
                    nodes[current][searching[current]].flow -= pushed_flow;
                    nodes[next][pair].flow += pushed_flow;
                    return Some(pushed_flow)
                }
            }
            searching[current] += 1;
        }
        None
    }
}
fn cal_max_flow(nodes: &mut Vec<Vec<Edge>>, source: usize, sink: usize) -> i64 {
    let mut depth = vec![-1; nodes.len()];
    let mut searching = vec![0; nodes.len()];
    let mut sum_flow = 0_i64;
    let mut has_flow = true;
    while has_flow {
        has_flow = false;
        bfs(nodes, source, sink, &mut depth);
        for i in 0 .. searching.len() {
            searching[i] = 0;
        }
        while let Some(flow) = dfs(nodes, source, sink, &depth, &mut searching, std::i32::MAX) {
            has_flow = true;
            sum_flow += flow as i64;
        }
    }
    sum_flow
}
fn make_flow_network(size: usize, graph: &Vec<(usize, usize, i32)>) -> Vec<Vec<Edge>> {
    let mut result = vec![Vec::new(); size];
    for &(a, b, c) in graph {
        let len_a = result[a].len();
        let len_b = result[b].len();
        result[a].push(Edge{to: b, pair: len_b, flow: c});
        result[b].push(Edge{to: a, pair: len_a, flow: c});
    }
    result
}
fn reset_flow_network(nodes: &mut Vec<Vec<Edge>>) {
    for i in 0 .. nodes.len() {
        for j in 0 .. nodes[i].len() {
            let e = nodes[i][j];
            if e.to > i {
                let flow = (e.flow + nodes[e.to][e.pair].flow) / 2;
                nodes[i][j].flow = flow;
                nodes[e.to][e.pair].flow = flow;
            }
        }
    }
}
fn cal_min_cost(size: usize, edges: Vec<(usize, usize, i32)>) -> i64 {
    let mut network = make_flow_network(size, &edges);
    let mut min_cost = std::i64::MAX;
    for i in 1 .. size {
        let cost = cal_max_flow(&mut network, 0, i);
        if cost < min_cost {
            min_cost = cost;
        }
        reset_flow_network(&mut network);
    }
    min_cost
}
fn main() {
    loop {
        let_all!(n: usize, m: usize);
        if n == 0 && m == 0 {
            return
        }
        let mut default_cost = 0_i64;
        let mut edges = Vec::with_capacity(m);
        for _ in 0 .. m {
            let_all!(x: usize, y: usize, c: i32);
            if c > 0 {
                edges.push((x, y, c));
            }else {
                default_cost += c as i64;
            }
        }
        println!("{}", cal_min_cost(n, edges) + default_cost);
    }
}