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
X
1
Y
1
C
1
...
X
m
Y
m
C
m
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
X
i
is an index of the room, the starting point of the passageway.
The second integer
Y
i
is an index of the room, the end point of the passageway.
The third integer
C
i
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 ≤
C
i
≤ 10,000
Y
1
...
Y
m
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

Submitted solutions:

code_snippet: #include <iostream>
#include <vector>
#include <algorithm>
#include <numeric>
#include <limits>
using namespace std;

long long stoer_wagner(vector<vector<long long>>& W) {
    int n = (int)W.size();
    vector<int> v(n);
    iota(v.begin(), v.end(), 0);
    long long best = numeric_limits<long long>::max();
    while (n > 1) {
        vector<long long> w(n, 0);
        vector<char> added(n, 0);
        int prev = -1, sel = -1;
        for (int it = 0; it < n; ++it) {
            sel = -1;
            for (int i = 0; i < n; ++i)
                if (!added[i] && (sel == -1 || w[i] > w[sel])) sel = i;
            if (added[sel]) break;
            added[sel] = 1;
            if (it == n - 1) {
                best = min(best, w[sel]);
                int a = sel, b = prev;
                if (b == -1) return best;
                for (int i = 0; i < n; ++i) if (i != a && i != b) {
                    W[v[b]][v[i]] += W[v[a]][v[i]];
                    W[v[i]][v[b]] = W[v[b]][v[i]];
                }
                v[sel] = v[n - 1];
                --n;
                break;
            }
            prev = sel;
            for (int i = 0; i < n; ++i) if (!added[i]) w[i] += W[v[sel]][v[i]];
        }
    }
    if (best == numeric_limits<long long>::max()) best = 0;
    return best;
}

int main() {
    ios::sync_with_stdio(false);
    cin.tie(nullptr);
    int n, m;
    while (cin >> n >> m) {
        if (n == 0 && m == 0) break;
        vector<vector<long long>> W(n, vector<long long>(n, 0));
        long long base = 0;
        for (int i = 0; i < m; ++i) {
            int x, y, c;
            cin >> x >> y >> c;
            if (c < 0) base += c;
            else if (x != y) {
                W[x][y] += c;
                W[y][x] += c;
            }
        }
        long long res = base + stoer_wagner(W);
        cout << res << "\n";
    }
    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3480
final_rank: 11

code_snippet: #include <iostream>
#include <string>
#include <cmath>
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <ctime>
#include <queue>
#include <stack>
#include <list>
#include <algorithm>

using namespace std;

#define typec long long
#define V 111
typec g[V][V], w[V];
typec a[V], v[V], na[V];

typec Stoer_Wagner(int n)
{
    typec i, j, pv, zj,I=1;
    typec best = I<<32;
    for (i = 0; i < n; i++) v[i] = i; // vertex: 0 ~ n-1
    while (n > 1)
    {
        for (a[v[0]] = 1, i = 1; i < n; i++)
        {
            a[v[i]] = 0;
            na[i - 1] = i;
            w[i] = g[v[0]][v[i]];

        }
        for (pv = v[0], i = 1; i < n; i++ )
        {
            for (zj = -1, j = 1; j < n; j++ )
                if (!a[v[j]] && (zj < 0 || w[j] > w[zj]))

                    zj = j;
            a[v[zj]] = 1;
            if (i == n - 1)
            {
                if (best > w[zj]) best = w[zj];
                for (i = 0; i < n; i++)
                    g[v[i]][pv] = g[pv][v[i]] += g[v[zj]][v[i]];
                v[zj] = v[--n];
                break;
            }
            pv = v[zj];
            for (j = 1; j < n; j++)
                if(!a[v[j]])
                    w[j] += g[v[zj]][v[j]];
        }
    }
    return best;
}
bool vis[111];
void dfs(int u,int n)
{
    for(int v=0;v<n;++v)
        if(g[u][v]!=0&&vis[v]==0)
    {
        vis[v]=1;
        dfs(v,n);
    }
}
bool ok(int n)
{
    for(int i=0;i<n;++i)
        if(vis[i]==0)return 1;
    return 0;
}
int main()
{
    //freopen("G:\\in.txt","r",stdin);
    int n, m, u, v, w;
    while(scanf("%d%d", &n, &m),n+m)
    {
        memset(g, 0, sizeof(g));
        typec ans=0;
        while(m --)
        {
            scanf("%d%d%d", &u, &v, &w);
            if(w<=0)ans+=w;
            else  g[v][u]= g[u][v] = w;

        }
       // memset(vis,0,sizeof(vis));
        //dfs(0,n);
        //if(ok(n))puts("0");
         printf("%lld\n", ans+Stoer_Wagner(n));
    }
    return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3584
final_rank: 9

code_snippet: #include<bits/stdc++.h>
#define N 105
using namespace std;

struct edge{
  int to, num;
};

int n, m;
vector<edge> G[N];
int A, B, minuscost;

int used[N], cost[N];

int dfs(int x){
  
  if(used[x]) return 0;
  used[x]=1;
  
  int res=0;
  
  for(int i=0;i<G[x].size();i++){
    if(A==G[x][i].num) continue;
    if(B==G[x][i].num) continue;
    res+=dfs(G[x][i].to);
  }
  
  return res+1;
}

void solve(){
  
  memset(used,0,sizeof(used));
  
  A=-1, B=-1;
  
  int nodesum=dfs(0);
  
  if(nodesum!=n){
    cout<<minuscost<<endl;
    return ;
  }
  
  int ans=(1e9);
  
  for(int i=0;i<m;i++){
    A=i;
    for(int j=i+1;j<m;j++){
      B=j;
      memset(used,0,sizeof(used));
      int r=dfs(0);
      if(r!=n) ans=min(ans, cost[A]+cost[B]+minuscost);
    }
    B=-1;
    memset(used,0,sizeof(used));
    int r=dfs(0);
    if(r!=n) ans=min(ans, cost[A]+minuscost);
  }
  
  cout<<ans<<endl;
}

int main(){

  while(1){
  
    cin>>n>>m;
    if(!n&&!m) break;
    
    minuscost=0;
  
    int cnt=0;
  
    for(int i=0;i<m;i++){
      int x, y, c;
      cin>>x>>y>>c;
      if(c<=0){
	minuscost+=c;
	continue;
      }
      cost[cnt]=c;
      G[x].push_back((edge){y,cnt});
      G[y].push_back((edge){x,cnt++});
    }

    m=cnt;
  
    solve();

    for(int i=0;i<n;i++) G[i].clear();
  }
  
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 3144
final_rank: 5

code_snippet: #include <stdio.h>
#include <cmath>
#include <algorithm>
#include <cfloat>
#include <stack>
#include <queue>
#include <vector>
#include <string>
#include <iostream>
#include <set>
#include <map>
#include <time.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define NUM 100

struct Info{
	Info(int arg_from,int arg_to,int arg_cost){
		from = arg_from;
		to = arg_to;
		cost = arg_cost;
	}
	int from,to,cost;
};

int N,M;

int boss[100],height[100];

int get_boss(int id){
	if(boss[id] == id)return id;
	else{
		return boss[id] = get_boss(boss[id]);
	}
}


void unite(int x,int y){
	int boss_x = get_boss(x);
	int boss_y = get_boss(y);

	if(boss_x == boss_y)return;

	if(height[x] > height[y]){

		boss[boss_y] = boss_x;

	}else if(height[x] < height[y]){

		boss[boss_x] = boss_y;

	}else{ //height[x] == height[y]

		boss[boss_y] = boss_x;
		height[x]++;
	}
}

void init(){
	for(int i = 0; i < N; i++){
		boss[i] = i;
		height[i] = 0;
	}
}

vector<Info> V;

void func(){

	init();
	V.clear();

	int from,to,cost;
	int ans = 0;

	for(int i = 0; i < M; i++){
		scanf("%d %d %d",&from,&to,&cost);
		if(cost < 0){
			ans  += cost;
		}else{
			unite(from,to);
			V.push_back(Info(from,to,cost));
		}
	}

	int group_num = 0;
	for(int i = 0; i < N; i++){
		if(get_boss(i) == i)group_num++;
	}
	if(group_num >= 2){
		printf("%d\n",ans);
		return;
	}

	int ans_1 = BIG_NUM;
	for(int i = 0; i < V.size(); i++){
		init();
		for(int k = 0; k < V.size(); k++){
			if(i == k)continue;
			unite(V[k].from,V[k].to);
		}
		group_num = 0;
		for(int k = 0; k < N; k++){
			if(get_boss(k) == k)group_num++;
		}
		if(group_num >= 2){
			ans_1 = min(ans_1,ans+V[i].cost);
		}
	}

	int ans_2 = BIG_NUM;

	for(int i = 0; i < V.size()-1; i++){
		for(int k = i+1; k < V.size(); k++){
			init();
			for(int p = 0; p < V.size(); p++){
				if(p == i || p == k)continue;
				unite(V[p].from,V[p].to);
			}
			group_num = 0;
			for(int p = 0; p < N; p++){
				if(get_boss(p) == p)group_num++;
			}
			if(group_num >= 2){
				ans_2 = min(ans_2,ans+V[i].cost+V[k].cost);
			}
		}
	}
	printf("%d\n",min(ans_1,ans_2));
}


int main(){

	while(true){
		scanf("%d %d",&N,&M);
		if(N == 0 && M == 0)break;

		func();
	}

	return 0;
}
accuracy: 1
time_ms: 20
memory_kb: 3144
final_rank: 8

code_snippet: #include <vector>
#include <numeric>
#include <algorithm>

class unionfind {
private:
	int size_;
	std::vector<int> parent;
	std::vector<int> rank;
public:
	unionfind() : size_(0), parent(std::vector<int>()), rank(std::vector<int>()) {};
	unionfind(int size__) : size_(size__), parent(std::vector<int>(size_)), rank(std::vector<int>(size_, 0)) {
		std::iota(parent.begin(), parent.end(), 0);
	}
	int size() { return size_; }
	int root(int x) {
		if (parent[x] == x) return x;
		return parent[x] = root(parent[x]);
	}
	bool same(int x, int y) {
		return root(x) == root(y);
	}
	void unite(int x, int y) {
		x = root(x); y = root(y);
		if (x == y) return;
		if (rank[x] < rank[y]) parent[x] = y;
		else if (rank[x] > rank[y]) parent[y] = x;
		else parent[y] = x, rank[x]++;
	}
};

#include <iostream>
using namespace std;
int n, m, x[109], y[109]; long long c[109]; bool used[109];
bool solve() {
	unionfind uf(n);
	for (int i = 0; i < m; i++) {
		if (used[i]) uf.unite(x[i], y[i]);
	}
	int s = uf.root(0);
	for (int i = 1; i < n; i++) {
		if (s != uf.root(i)) return true;
	}
	return false;
}
int main() {
	while (cin >> n >> m, n) {
		int sum = 0;
		for (int i = 0; i < m; i++) {
			cin >> x[i] >> y[i] >> c[i];
			if (c[i] > 0) used[i] = true;
			else used[i] = false, sum += c[i];
		}
		long long ret = 1LL << 60;
		if (solve()) ret = sum;
		for (int i = 0; i < m; i++) {
			if (!used[i]) continue;
			used[i] = false;
			if (solve()) ret = min(ret, sum + c[i]);
			used[i] = true;
		}
		for (int i = 0; i < m; i++) {
			if (!used[i]) continue;
			used[i] = false;
			for (int j = i + 1; j < m; j++) {
				if (!used[j]) continue;
				used[j] = false;
				if (solve()) ret = min(ret, sum + c[i] + c[j]);
				used[j] = true;
			}
			used[i] = true;
		}
		cout << ret << endl;
	}
	return 0;
}
accuracy: 1
time_ms: 40
memory_kb: 2932
final_rank: 15

code_snippet: #include <cstdlib>
#include <cmath>
#include <climits>
#include <cfloat>
#include <map>
#include <set>
#include <iostream>
#include <string>
#include <vector>
#include <algorithm>
#include <sstream>
#include <complex>
#include <stack>
#include <queue>
#include <cstdio>
#include <cstring>
#include <iterator>
#include <bitset>
#include <unordered_set>
#include <unordered_map>
#include <fstream>
#include <iomanip>
//#include <utility>
//#include <memory>
//#include <functional>
//#include <deque>
//#include <cctype>
//#include <ctime>
//#include <numeric>
//#include <list>
//#include <iomanip>

//#if __cplusplus >= 201103L
//#include <array>
//#include <tuple>
//#include <initializer_list>
//#include <forward_list>
//
//#define cauto const auto&
//#else

//#endif

using namespace std;


typedef long long ll;
typedef pair<int,int> pii;
typedef pair<ll,ll> pll;

typedef vector<int> vint;
typedef vector<vector<int> > vvint;
typedef vector<long long> vll, vLL;
typedef vector<vector<long long> > vvll, vvLL;

#define VV(T) vector<vector< T > >

template <class T>
void initvv(vector<vector<T> > &v, int a, int b, const T &t = T()){
    v.assign(a, vector<T>(b, t));
}

template <class F, class T>
void convert(const F &f, T &t){
    stringstream ss;
    ss << f;
    ss >> t;
}

#undef _P
#define _P(...) (void)printf(__VA_ARGS__)
#define reep(i,a,b) for(int i=(a);i<(b);++i)
#define rep(i,n) reep((i),0,(n))
#define ALL(v) (v).begin(),(v).end()
#define PB push_back
#define F first
#define S second
#define mkp make_pair
#define RALL(v) (v).rbegin(),(v).rend()
#define DEBUG
#ifdef DEBUG
#define dump(x)  cout << #x << " = " << (x) << endl;
#define debug(x) cout << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
#else
#define dump(x) 
#define debug(x) 
#endif
#define LDcout(x,n) fixed<<setprecision(n)<<x

#define MOD 1000000007LL
#define EPS 1e-8
static const int INF=1<<24;
//max flow (dinic)
template<class V> class MaxFlow_dinic{
public:
    struct edge{int to,reve;V cap;};
    static const int MV = 1100;
    vector<edge> E[MV];
    int itr[MV],lev[MV];

    void add_edge(int x,int y,V cap,bool undir=false){
        E[x].push_back((edge){y,(int)E[y].size(),cap});
        E[y].push_back((edge){x,(int)E[x].size()-1,undir?cap:0});
    }

    void bfs(int cur){
        memset(lev,0xff,sizeof(lev));
        queue<int> q;
        lev[cur]=0;
        q.push(cur);
        while(q.size()){
            int v=q.front();
            q.pop();
            for(__typeof(E[v].begin()) e=E[v].begin();e!=E[v].end();e++) if(e->cap>0&&lev[e->to]<0) lev[e->to]=lev[v]+1,q.push(e->to);
        }
    }

    V dfs(int from,int to,V cf){
        if(from==to){
            return cf;
        }
        for(;itr[from]<E[from].size();itr[from]++){
            edge* e=&E[from][itr[from]];
            if(e->cap>0&&lev[from]<lev[e->to]){
                V f=dfs(e->to,to,min(cf,e->cap));
                if(f>0){
                    e->cap-=f;
                    E[e->to][e->reve].cap += f;
                    return f;
                }
            }
        }
        return 0;
    }

    V maxflow(int from,int to){
        V fl=0,tf;
        while(1){
            bfs(from);
            if(lev[to]<0) return fl;
            memset(itr,0,sizeof(itr));
            while((tf=dfs(from,to,numeric_limits<V>::max()))>0) fl+=tf;
        }
    }
};
void mainmain(){
	int n,m;
	while(cin>>n>>m,n||m){
		ll ans=INT_MAX;
		vint a(m),b(m),c(m);
		rep(i,m) cin>>a[i]>>b[i]>>c[i];
		reep(i,1,n){
			MaxFlow_dinic<ll> mf;
			int tmp=0;
			rep(j,m){
				if(c[j]<0) tmp+=c[j];
				else mf.add_edge(a[j],b[j],(ll)c[j],true);
			}
			ans=min(ans,tmp+mf.maxflow(0,i));
		}
		cout<<ans<<endl;
	}
}


signed main() {
	ios_base::sync_with_stdio(false);
  	cout<<fixed<<setprecision(0);
    mainmain();
}
accuracy: 1
time_ms: 20
memory_kb: 1268
final_rank: 7

code_snippet: #include <bits/stdc++.h>
using namespace std;

#define dump(...) cout<<"# "<<#__VA_ARGS__<<'='<<(__VA_ARGS__)<<endl
#define repi(i,a,b) for(int i=int(a);i<int(b);i++)
#define peri(i,a,b) for(int i=int(b);i-->int(a);)
#define rep(i,n) repi(i,0,n)
#define per(i,n) peri(i,0,n)
#define all(c) begin(c),end(c)
#define mp make_pair
#define mt make_tuple

typedef unsigned int uint;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int,int> pii;
typedef vector<int> vi;
typedef vector<vi> vvi;
typedef vector<ll> vl;
typedef vector<vl> vvl;
typedef vector<double> vd;
typedef vector<vd> vvd;
typedef vector<string> vs;

template<typename T1,typename T2>
ostream& operator<<(ostream& os,const pair<T1,T2>& p){
	return os<<'('<<p.first<<','<<p.second<<')';
}

template<typename Tuple>
void print_tuple(ostream&,const Tuple&){}
template<typename Car,typename... Cdr,typename Tuple>
void print_tuple(ostream& os,const Tuple& t){
	print_tuple<Cdr...>(os,t);
	os<<(sizeof...(Cdr)?",":"")<<get<sizeof...(Cdr)>(t);
}
template<typename... Args>
ostream& operator<<(ostream& os,const tuple<Args...>& t){
	print_tuple<Args...>(os<<'(',t);
	return os<<')';
}

template<typename Ch,typename Tr,typename C,typename=decltype(begin(C()))>
basic_ostream<Ch,Tr>& operator<<(basic_ostream<Ch,Tr>& os,const C& c){
	os<<'[';
	for(auto i=begin(c);i!=end(c);++i)
		os<<(i==begin(c)?"":" ")<<*i;
	return os<<']';
}

constexpr int INF=1e9;
constexpr int MOD=1e9+7;
constexpr double EPS=1e-9;

struct UnionFind{
	vi data;
	UnionFind(int n):data(n,-1){}
	int Find(int i){
		return data[i]<0?i:(data[i]=Find(data[i]));
	}
	bool Unite(int a,int b){
		a=Find(a),b=Find(b);
		if(a==b) return false;
		if(-data[a]<-data[b]) swap(a,b);
		data[a]+=data[b];
		data[b]=a;
		return true;
	}
	int Size(int i){
		return -data[Find(i)];
	}
};

struct Edge{
	int src,dst,weight;
	Edge(){}
	Edge(int s,int d,int w):src(s),dst(d),weight(w){}
};
typedef vector<vector<Edge>> Graph;

int main()
{
	for(int n,m;cin>>n>>m && n|m;){
		vector<Edge> es;
		int neg=0;
		rep(i,m){
			int u,v,w; cin>>u>>v>>w;
			if(w<=0) neg+=w;
			else es.emplace_back(u,v,w);
		}
		m=es.size();
		
		int res=INF;
		{
			UnionFind uf(n);
			int cc=n;
			rep(i,m)
				cc-=uf.Unite(es[i].src,es[i].dst);
			if(cc>=2) res=0;
		}
		{
			rep(i,m){
				vi use(m,1); use[i]=0;
				UnionFind uf(n);
				int cc=n;
				rep(j,m) if(use[j])
					cc-=uf.Unite(es[j].src,es[j].dst);
				if(cc>=2) res=min(res,es[i].weight);
			}
		}
		{
			rep(i,m) repi(j,i+1,m){
				vi use(m,1); use[i]=use[j]=0;
				UnionFind uf(n);
				int cc=n;
				rep(k,m) if(use[k])
					cc-=uf.Unite(es[k].src,es[k].dst);
				if(cc>=2) res=min(res,es[i].weight+es[j].weight);
			}
		}
		cout<<neg+res<<endl;
	}
}
accuracy: 1
time_ms: 60
memory_kb: 1200
final_rank: 17

code_snippet: #define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cstdio>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

const int tx[] = {0,1,0,-1};
const int ty[] = {-1,0,1,0};

struct Node {
  int to;
  int idx;
  int flow;
  Node(int to,int idx,int flow) :
    to(to),idx(idx),flow(flow) {}
};

class FordFulkerson {
private:
  vector<Node>* _graph;
  bool* _used;
  int _size;

  int dfs(int src,int flow,int sink){
    if(src == sink) return flow;

    _used[src] = true;
    for(int i= 0;i < _graph[src].size();i++){
      Node& e = _graph[src][i];
      if(_used[e.to]) continue;
      if(e.flow <= 0) continue;
      int d = dfs(e.to,min(flow,e.flow),sink);
      if(d <= 0) continue;

      Node& rev_e = _graph[e.to][e.idx];
      e.flow -= d;
      rev_e.flow += d;
      return d;
    }
    return 0;
  }

public:  
  FordFulkerson(int n) {
    _size = n;
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
  }

  ~FordFulkerson(){
    delete[] _graph;
    delete[] _used;
  }

  FordFulkerson(const FordFulkerson& f){
    _size = f.size();
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
    fill((bool*)_used,(bool*)_used + _size,false);

    for(int i = 0; i < f.size(); i++){
      for(int j = 0; j < f.graph()[i].size(); j++){
        _graph[i].push_back(f.graph()[i][j]);
      }
    }
  }

  void add_edge(int from,int to,int flow) {
    _graph[from].push_back(Node(to,_graph[to].size(),flow));
    _graph[to].push_back(Node(from,_graph[from].size()-1,flow));
  }

  int compute_maxflow(int src,int sink){
    int res = 0;

    while(true){
      fill((bool*)_used,(bool*)_used + _size,false);
      int tmp = dfs(src,numeric_limits<int>::max(),sink);
      if(tmp == 0) break;
      res += tmp;
    }
    return res;
  }

  int size() const{
    return _size;
  }
  vector<Node>* graph() const{
    return _graph;
  }
};

int main(){
  int num_of_houses;
  int num_of_paths;
  while(~scanf("%d %d",&num_of_houses,&num_of_paths)){
    if(num_of_houses == 0 && num_of_paths == 0) break;

    FordFulkerson ff(num_of_houses);
    int bonus = 0;

    for(int path_i = 0; path_i < num_of_paths; path_i++){
      int from,to;
      int cost;
      scanf("%d %d %d",&from,&to,&cost);
      if(cost < 0) bonus += cost; 
      ff.add_edge(from,to,max(0,cost));
    }

    int res = numeric_limits<int>::max();

    for(int house_i = 1; house_i< num_of_houses; house_i++){
      FordFulkerson tmp(ff);
      res = min(res,tmp.compute_maxflow(0,house_i));
    }
    printf("%d\n",bonus + res);
  }
}
accuracy: 1
time_ms: 30
memory_kb: 1208
final_rank: 10

code_snippet: #define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cstdio>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

const int tx[] = {0,1,0,-1};
const int ty[] = {-1,0,1,0};

struct Node {
  int to;
  int idx;
  int flow;
  Node(int to,int idx,int flow) :
    to(to),idx(idx),flow(flow) {}
};

class FordFulkerson {
private:
  vector<Node>* _graph;
  bool* _used;
  int _size;

  int dfs(int src,int flow,int sink){
    if(src == sink) return flow;

    _used[src] = true;
    for(int i= 0;i < _graph[src].size();i++){
      Node& e = _graph[src][i];
      if(_used[e.to]) continue;
      if(e.flow <= 0) continue;
      int d = dfs(e.to,min(flow,e.flow),sink);
      if(d <= 0) continue;

      Node& rev_e = _graph[e.to][e.idx];
      e.flow -= d;
      rev_e.flow += d;
      return d;
    }
    return 0;
  }

public:  
  FordFulkerson(int n) {
    _size = n;
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
  }
  FordFulkerson(const FordFulkerson& f){
    _size = f.size();
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
    fill((bool*)_used,(bool*)_used + _size,false);

    for(int i = 0; i < f.size(); i++){
      for(int j = 0; j < f.graph()[i].size(); j++){
        _graph[i].push_back(f.graph()[i][j]);
      }
    }
  }

  void add_edge(int from,int to,int flow) {
    _graph[from].push_back(Node(to,_graph[to].size(),flow));
    _graph[to].push_back(Node(from,_graph[from].size()-1,flow));
  }

  int compute_maxflow(int src,int sink){
    int res = 0;

    while(true){
      fill((bool*)_used,(bool*)_used + _size,false);
      int tmp = dfs(src,numeric_limits<int>::max(),sink);
      if(tmp == 0) break;
      res += tmp;
    }
    return res;
  }

  int size() const{
    return _size;
  }
  vector<Node>* graph() const{
    return _graph;
  }
};

int main(){
  int num_of_houses;
  int num_of_paths;
  while(~scanf("%d %d",&num_of_houses,&num_of_paths)){
    if(num_of_houses == 0 && num_of_paths == 0) break;

    FordFulkerson ff(num_of_houses);
    int bonus = 0;

    for(int path_i = 0; path_i < num_of_paths; path_i++){
      int from,to;
      int cost;
      scanf("%d %d %d",&from,&to,&cost);
      if(cost < 0) bonus += cost; 
      ff.add_edge(from,to,max(0,cost));
    }

    int res = numeric_limits<int>::max();

    for(int house_i = 1; house_i< num_of_houses; house_i++){
      FordFulkerson tmp(ff);
      res = min(res,tmp.compute_maxflow(0,house_i));
    }
    printf("%d\n",bonus + res);
  }
}
accuracy: 1
time_ms: 30
memory_kb: 24904
final_rank: 20

code_snippet: #define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cstdio>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

const int tx[] = {0,1,0,-1};
const int ty[] = {-1,0,1,0};

struct Node {
  int to;
  int idx;
  int flow;
  Node(int to,int idx,int flow) :
    to(to),idx(idx),flow(flow) {}
};

class FordFulkerson {
private:
  vector<Node>* _graph;
  bool* _used;
  int _size;

  int dfs(int src,int flow,int sink){
    if(src == sink) return flow;

    _used[src] = true;
    for(int i= 0;i < _graph[src].size();i++){
      Node& e = _graph[src][i];
      if(_used[e.to]) continue;
      if(e.flow <= 0) continue;
      int d = dfs(e.to,min(flow,e.flow),sink);
      if(d <= 0) continue;

      Node& rev_e = _graph[e.to][e.idx];
      e.flow -= d;
      rev_e.flow += d;
      return d;
    }
    return 0;
  }

public:  
  FordFulkerson(int n) {
    _size = n;
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
  }
  FordFulkerson(const FordFulkerson& f){
    _size = f.size();
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
    fill((bool*)_used,(bool*)_used + _size,false);

    for(int i = 0; i < f.size(); i++){
      for(int j = 0; j < f.graph()[i].size(); j++){
        _graph[i].push_back(f.graph()[i][j]);
      }
    }
  }

  void add_edge(int from,int to,int flow) {
    _graph[from].push_back(Node(to,_graph[to].size(),flow));
    _graph[to].push_back(Node(from,_graph[from].size()-1,flow));
  }

  int compute_maxflow(int src,int sink){
    int res = 0;

    while(true){
      fill((bool*)_used,(bool*)_used + _size,false);
      int tmp = dfs(src,numeric_limits<int>::max(),sink);
      if(tmp == 0) break;
      res += tmp;
    }
    return res;
  }

  int size() const{
    return _size;
  }
  vector<Node>* graph() const{
    return _graph;
  }
};

class UnionFindTree {
private:
  int* par;
  int* rank;
public:
  UnionFindTree(int n){
    par = new int[n]();
    rank = new int[n]();
    for(int i=0;i<n;i++){
      par[i] = i;
      rank[i] = 0;
    }
  }

  ~UnionFindTree(){
    delete[] rank;
    delete[] par;
  }

  int find(int x){
    if(par[x] == x){
      return x;
    } else {
      return par[x] = find(par[x]);
    }
  }

  void unite(int x,int y){
    x = find(x);
    y = find(y);
    if (x == y) return;
    par[x] = y;
  }

  bool same(int x,int y){
    return find(x) == find(y);
  }
};

int main(){
  int num_of_houses;
  int num_of_paths;
  while(~scanf("%d %d",&num_of_houses,&num_of_paths)){
    if(num_of_houses == 0 && num_of_paths == 0) break;

    FordFulkerson ff(num_of_houses);
    UnionFindTree uft(num_of_houses);

    int bonus = 0;

    for(int path_i = 0; path_i < num_of_paths; path_i++){
      int from,to;
      int cost;
      scanf("%d %d %d",&from,&to,&cost);
      if(cost < 0) bonus += cost; 
      ff.add_edge(from,to,max(0,cost));
      uft.unite(from,to);
    }

    int tree_count = 0;
    bool visited[101];
    memset(visited,false,sizeof(visited));
    for(int house_i = 0; house_i< num_of_houses; house_i++){
      if(!visited[uft.find(house_i)]) tree_count++;
      visited[uft.find(house_i)] = true;
    }

    int res = numeric_limits<int>::max();

    if(tree_count >= 2){
      res = 0;
    }
    else{
      for(int house_i = 0; house_i< num_of_houses; house_i++){
        int house_j = uft.find(house_i);
        if(house_i == house_j) continue;
        FordFulkerson tmp(ff);
        res = min(res,tmp.compute_maxflow(house_i,house_j));
      }
    }
    printf("%d\n",bonus + res);
  }
}
accuracy: 1
time_ms: 10
memory_kb: 10764
final_rank: 13

code_snippet: #define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cstdio>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

const int tx[] = {0,1,0,-1};
const int ty[] = {-1,0,1,0};

struct Node {
  int to;
  int idx;
  int flow;
  Node(int to,int idx,int flow) :
    to(to),idx(idx),flow(flow) {}
};

class FordFulkerson {
private:
  vector<Node>* _graph;
  bool* _used;
  int _size;

  int dfs(int src,int flow,int sink){
    if(src == sink) return flow;

    _used[src] = true;
    for(int i= 0;i < _graph[src].size();i++){
      Node& e = _graph[src][i];
      if(_used[e.to]) continue;
      if(e.flow <= 0) continue;
      int next_flow = min(flow,e.flow);
      int d = dfs(e.to,next_flow,sink);
      if(d <= 0) continue;

      Node& rev_e = _graph[e.to][e.idx];
      e.flow -= d;
      rev_e.flow += d;
      return d;
    }
    return 0;
  }

public:  
  FordFulkerson(int n) {
    _size = n;
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
  }
  FordFulkerson(const FordFulkerson& f){
    _size = f.size();
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
    fill((bool*)_used,(bool*)_used + _size,false);

    for(int i = 0; i < f.size(); i++){
      for(int j = 0; j < f.graph()[i].size(); j++){
        _graph[i].push_back(f.graph()[i][j]);
      }
    }
  }

  void add_edge(int from,int to,int flow) {
    _graph[from].push_back(Node(to,_graph[to].size(),flow));
    _graph[to].push_back(Node(from,_graph[from].size()-1,flow));
  }

  int compute_maxflow(int src,int sink){
    int res = 0;

    while(true){
      fill((bool*)_used,(bool*)_used + _size,false);
      int tmp = dfs(src,numeric_limits<int>::max(),sink);
      if(tmp == 0) break;
      res += tmp;
    }
    return res;
  }

  int size() const{
    return _size;
  }
  vector<Node>* graph() const{
    return _graph;
  }
};

class UnionFindTree {
private:
  int* par;
  int* rank;
public:
  UnionFindTree(int n){
    par = new int[n]();
    rank = new int[n]();
    for(int i=0;i<n;i++){
      par[i] = i;
      rank[i] = 0;
    }
  }

  ~UnionFindTree(){
    delete[] rank;
    delete[] par;
  }

  int find(int x){
    if(par[x] == x){
      return x;
    } else {
      return par[x] = find(par[x]);
    }
  }

  void unite(int x,int y){
    x = find(x);
    y = find(y);
    if (x == y) return;
    par[x] = y;
  }

  bool same(int x,int y){
    return find(x) == find(y);
  }
};

int main(){
  int num_of_houses;
  int num_of_paths;
  while(~scanf("%d %d",&num_of_houses,&num_of_paths)){
    if(num_of_houses == 0 && num_of_paths == 0) break;

    FordFulkerson ff(num_of_houses);
    UnionFindTree uft(num_of_houses);

    int bonus = 0;

    for(int path_i = 0; path_i < num_of_paths; path_i++){
      int from,to;
      int cost;
      scanf("%d %d %d",&from,&to,&cost);
      if(cost < 0) bonus += cost; 
      ff.add_edge(from,to,max(0,cost));
      uft.unite(from,to);
    }

    int tree_count = 0;
    bool visited[101];
    memset(visited,false,sizeof(visited));
    for(int house_i = 0; house_i< num_of_houses; house_i++){
      if(!visited[uft.find(house_i)]) tree_count++;
      visited[uft.find(house_i)] = true;
    }

    int res = numeric_limits<int>::max();

    if(tree_count >= 2){
      res = 0;
    }
    else{
      for(int house_i = 0; house_i< num_of_houses; house_i++){
        int house_j = uft.find(house_i);
        if(house_i == house_j) continue;
        FordFulkerson tmp(ff);
        res = min(res,tmp.compute_maxflow(house_i,house_j));
      }
    }
    printf("%d\n",bonus + res);
  }
}
accuracy: 1
time_ms: 10
memory_kb: 10764
final_rank: 13

code_snippet: #define _USE_MATH_DEFINES
#define INF 100000000
#include <iostream>
#include <sstream>
#include <cmath>
#include <cstdlib>
#include <algorithm>
#include <queue>
#include <stack>
#include <limits>
#include <map>
#include <string>
#include <cstring>
#include <set>
#include <deque>
#include <bitset>
#include <list>
#include <cstdio>

using namespace std;

typedef long long ll;
typedef pair <int,int> P;
typedef pair <int,P> PP;

static const double EPS = 1e-8;

const int tx[] = {0,1,0,-1};
const int ty[] = {-1,0,1,0};

struct Node {
  int to;
  int idx;
  int flow;
  Node(int to,int idx,int flow) :
    to(to),idx(idx),flow(flow) {}
};

class FordFulkerson {
private:
  vector<Node>* _graph;
  bool* _used;
  int _size;

  int dfs(int src,int flow,int sink){
    if(src == sink) return flow;

    int res = 0;
    _used[src] = true;
    for(int i= 0;i < _graph[src].size();i++){
      Node& e = _graph[src][i];
      if(_used[e.to]) continue;
      if(e.flow <= 0) continue;
      int d = dfs(e.to,min(flow,e.flow),sink);
      if(d > 0){
        Node& rev_e = _graph[e.to][e.idx];
        e.flow -= d;
        rev_e.flow += d;
        return d;
      }
    }
    return 0;
  }

public:  
  FordFulkerson(int n) {
    _size = n;
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
  }
  FordFulkerson(const FordFulkerson& f){
    _size = f.size();
    _graph = new vector<Node>[_size];
    _used = new bool[_size];
    fill((bool*)_used,(bool*)_used + _size,false);

    for(int i = 0; i < f.size(); i++){
      for(int j = 0; j < f.graph()[i].size(); j++){
        _graph[i].push_back(f.graph()[i][j]);
      }
    }
  }

  void add_edge(int from,int to,int flow) {
    _graph[from].push_back(Node(to,_graph[to].size(),flow));
    _graph[to].push_back(Node(from,_graph[from].size()-1,flow));
  }

  int compute_maxflow(int src,int sink){
    int res = 0;

    while(true){
      fill((bool*)_used,(bool*)_used + _size,false);
      int tmp = dfs(src,numeric_limits<int>::max(),sink);
      if(tmp == 0) break;
      res += tmp;
    }
    return res;
  }

  int size() const{
    return _size;
  }
  vector<Node>* graph() const{
    return _graph;
  }
};

class UnionFindTree {
private:
  int* par;
  int* rank;
public:
  UnionFindTree(int n){
    par = new int[n]();
    rank = new int[n]();
    for(int i=0;i<n;i++){
      par[i] = i;
      rank[i] = 0;
    }
  }

  ~UnionFindTree(){
    delete[] rank;
    delete[] par;
  }

  int find(int x){
    if(par[x] == x){
      return x;
    } else {
      return par[x] = find(par[x]);
    }
  }

  void unite(int x,int y){
    x = find(x);
    y = find(y);
    if (x == y) return;
    par[x] = y;
  }

  bool same(int x,int y){
    return find(x) == find(y);
  }
};

int main(){
  int num_of_houses;
  int num_of_paths;
  while(~scanf("%d %d",&num_of_houses,&num_of_paths)){
    if(num_of_houses == 0 && num_of_paths == 0) break;

    FordFulkerson ff(num_of_houses);
    UnionFindTree uft(num_of_houses);

    int bonus = 0;

    for(int path_i = 0; path_i < num_of_paths; path_i++){
      int from,to;
      int cost;
      scanf("%d %d %d",&from,&to,&cost);
      if(cost < 0) bonus += cost; 
      ff.add_edge(from,to,max(0,cost));
      uft.unite(from,to);
    }

    int tree_count = 0;
    bool visited[101];
    memset(visited,false,sizeof(visited));
    for(int house_i = 0; house_i< num_of_houses; house_i++){
      if(!visited[uft.find(house_i)]) tree_count++;
      visited[uft.find(house_i)] = true;
    }

    int res = numeric_limits<int>::max();

    if(tree_count >= 2){
      res = 0;
    }
    else{
      for(int house_i = 0; house_i< num_of_houses; house_i++){
        int house_j = uft.find(house_i);
        if(house_i == house_j) continue;
        FordFulkerson tmp(ff);
        res = min(res,tmp.compute_maxflow(house_i,house_j));
      }
    }
    printf("%d\n",bonus + res);
  }
}
accuracy: 1
time_ms: 10
memory_kb: 10760
final_rank: 12

code_snippet: #include<stdio.h>
#include<algorithm>
#include<vector>
#include<queue>
using namespace std;
const int D_MAX_V=210;
const int D_v_size=210;
struct D_wolf{
	int t,r;
	long long c;
	D_wolf(){t=c=r=0;}
	D_wolf(int t1,long long c1,int r1){
		t=t1;c=c1;r=r1;
	}
};
vector<D_wolf>D_G[D_MAX_V];
int D_level[D_MAX_V];
int D_iter[D_MAX_V];

void add_edge(int from,int to,long long cap){
	D_G[from].push_back(D_wolf(to,cap,D_G[to].size()));
	D_G[to].push_back(D_wolf(from,0,D_G[from].size()-1));
}
void D_bfs(int s){
	for(int i=0;i<D_v_size;i++)D_level[i]=-1;
	queue<int> Q;
	D_level[s]=0;
	Q.push(s);
	while(Q.size()){
		int v=Q.front();
		Q.pop();
		for(int i=0;i<D_G[v].size();i++){
			if(D_G[v][i].c>0&&D_level[D_G[v][i].t]<0){
				D_level[D_G[v][i].t]=D_level[v]+1;
				Q.push(D_G[v][i].t);
			}
		}
	}
}
long long D_dfs(int v,int t,long long f){
	if(v==t)return f;
	for(;D_iter[v]<D_G[v].size();D_iter[v]++){
		int i=D_iter[v];
		if(D_G[v][i].c>0&&D_level[v]<D_level[D_G[v][i].t]){
			long long d=D_dfs(D_G[v][i].t,t,min(f,D_G[v][i].c));
			if(d>0){
				D_G[v][i].c-=d;
				D_G[D_G[v][i].t][D_G[v][i].r].c+=d;
				return d;
			}
		}
	}
	return 0;
}
long long max_flow(int s,int t){
	long long flow=0;
	for(;;){
		D_bfs(s);
		if(D_level[t]<0)return flow;
		for(int i=0;i<D_v_size;i++)D_iter[i]=0;
		long long f;
		while((f=D_dfs(s,t,9999999999999LL))>0){flow+=f;}
	}
	return 0;
}
long long INF=9999999999999LL;
int p[30000];
int q[30000];
int r[30000];
int main(){
	int a,b;
	while(scanf("%d%d",&a,&b),a){
		for(int i=0;i<b;i++){
			scanf("%d%d%d",p+i,q+i,r+i);
		}
		long long ret=999999999999999LL;
		for(int i=1;i<a;i++){
			for(int j=0;j<D_MAX_V;j++){
				D_G[j].clear();
				D_iter[j]=D_level[j]=0;
			}
			long long tmp=0;
		/*	for(int j=0;j<a;j++){
				add_edge(j,j+a,INF);
				if(j==0)add_edge(s,j,INF);
				else add_edge(s,j,0);
				if(j==i)add_edge(j+a,t,INF);
				else add_edge(j+a,t,0);
			}*/
			for(int j=0;j<b;j++){
				if(r[j]<=0){
					tmp+=r[j];continue;
				}
				add_edge(p[j],q[j],r[j]);
				add_edge(q[j],p[j],r[j]);
			}
			ret=min(ret,tmp+max_flow(0,i));
		}
		printf("%lld\n",ret);
	}
}
accuracy: 1
time_ms: 20
memory_kb: 1092
final_rank: 6

code_snippet: #include <stdio.h>
#include <string.h>
#include <algorithm>
using namespace std;


const int inf = 0x3f3f3f3f ;
const int maxw = 1000 ;
int g[105][105] , w[105] ;
int a[105] , v[105] , na[105] ;
int n , m ;
int mincut( int n ) {
	int i , j, pv , zj ;
	int best = inf ;
	for( i = 0 ; i < n; i ++ ) {
		v[i] = i ;
	}
	while( n > 1 ) {
		for( a[v[0]] = 1 , i = 1 ; i < n; i ++ ) {
			a[v[i]] = 0 ; na[i-1] = i ;
			w[i] = g[v[0]][v[i]] ;
		}
		for( pv = v[0] ,i = 1 ; i < n ; i ++ ) {
			for( zj = -1 , j = 1 ; j < n ; j ++ ) 
				if( !a[v[j]] && (zj<0||w[j]>w[zj]))
					zj = j ;
				a[v[zj]] = 1 ;
				if( i == n - 1 ) {
					if( best > w[zj] ) best = w[zj] ;
					for( i = 0 ; i < n;  i++ ) {
						g[v[i]][pv] = g[pv][v[i]] +=g[v[zj]][v[i]] ;
					}
					v[zj] = v[--n] ;
					break;
				}
				pv = v[zj] ;
				for( j = 1 ; j < n; j ++ ) if( !a[v[j]])
					w[j] += g[v[zj]][v[j]] ;
		}
	}
	return best ;
}

int main(){
	while( scanf( "%d%d" , &n , &m ) != EOF ) {
		if( n == 0 && m == 0 ) break;
		memset( g , 0 , sizeof(g) ) ;
		int ans = 0 ;
		int i ;
		for( i = 1 ; i <= m ;i ++ ) {
			int from , to ,val ;
			scanf( "%d%d%d" , &from , &to , &val ) ;
			if( val < 0 ) {
				ans += val ;
				continue ;
			}
			if( g[from][to] == inf ) {
				g[from][to] = val ;
			}else{
				g[from][to] += val ;
			}
			g[to][from] = g[from][to] ;
		}
		printf( "%d\n" , ans + mincut(n) )  ;
	}
	return 0 ;
}
accuracy: 1
time_ms: 60
memory_kb: 1076
final_rank: 16

code_snippet: #include<iostream>
#include<vector>
#include<algorithm>
#include<climits>

#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX 200

using namespace std;

struct Data{
  int from,to,cost,index;
  Data(int from=-1,int to=-1,int cost=-1,int index=-1):from(from),to(to),cost(cost),index(index){}
};

int V,E;
vector<Data> G[MAX];
bool visited[MAX];

void isconnect(int cur,int &counter,int *ban){
  if(visited[cur])return;
  visited[cur] = true;
  counter++;
  rep(i,G[cur].size()){
    if( ban[0] == G[cur][i].index || ban[1] == G[cur][i].index ) continue;
    isconnect(G[cur][i].to,counter,ban);
  }
}

int main(){
  while(cin >> V >> E,V|E){
    Data *input = new Data[E];
    int mincost = IINF,coef = 0;
    rep(i,V)G[i].clear();
    rep(i,E){
      cin >> input[i].from >> input[i].to >> input[i].cost;
      input[i].index = i;
      if( input[i].cost < 0 ) coef += input[i].cost;
      else {
	G[input[i].from].push_back(input[i]);
	G[input[i].to].push_back(Data(input[i].to,input[i].from,input[i].cost,input[i].index));
      }
    }

    int counter = 0;
    int ban[2] = {-1,-1};
    rep(i,V)visited[i] = false;
    isconnect(0,counter,ban);
    if(counter != V)mincost = min(mincost,coef);

    rep(i,E){
      if( input[i].cost < 0 ) continue;
      rep(j,E){
	if( input[j].cost < 0 ) continue;
	rep(k,V)visited[k] = false;
	ban[0] = i, ban[1] = j;
	counter = 0;
	isconnect(0,counter,ban);
	if( counter != V )mincost = min(mincost,coef+input[i].cost+((i==j)?0:input[j].cost));
      }
    }
    cout << mincost << endl;

    delete [] input;
  }
  return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 1228
final_rank: 19

code_snippet: #include<iostream>
#include<cmath>
#include<cstdio>
#include<vector>
#include<algorithm>
#include<cassert>
#include<climits>
#include<map>
#include<set>

#define REP(i,s,n) for(int i=s;i<n;i++)
#define rep(i,n) REP(i,0,n)
#define IINF (INT_MAX)
#define MAX 200

using namespace std;

struct Data{
  int from,to,cost,index;
  Data(int from=-1,int to=-1,int cost=-1,int index=-1):from(from),to(to),cost(cost),index(index){}
};

int V,E;
vector<Data> G[MAX];
bool visited[MAX];

void isconnect(int cur,int &counter,int *ban){
  if(visited[cur])return;
  visited[cur] = true;
  counter++;
  rep(i,G[cur].size()){
    if( ban[0] == G[cur][i].index || ban[1] == G[cur][i].index ) continue;
    isconnect(G[cur][i].to,counter,ban);
  }
}

int main(){
  while(cin >> V >> E,V|E){
    Data *input = new Data[E];
    int mincost = IINF,coef = 0;
    rep(i,V)G[i].clear();
    rep(i,E){
      cin >> input[i].from >> input[i].to >> input[i].cost;
      input[i].index = i;
      if( input[i].cost < 0 ) coef += input[i].cost;
      else {
	G[input[i].from].push_back(input[i]);
	G[input[i].to].push_back(Data(input[i].to,input[i].from,input[i].cost,input[i].index));
      }
    }

    int counter = 0;
    int ban[2] = {-1,-1};
    rep(i,V)visited[i] = false;
    isconnect(0,counter,ban);
    if(counter != V)mincost = min(mincost,coef);

    rep(i,E){
      if( input[i].cost < 0 ) continue;
      rep(j,E){
	if( input[j].cost < 0 ) continue;
	rep(k,V)visited[k] = false;
	ban[0] = i, ban[1] = j;
	counter = 0;
	isconnect(0,counter,ban);
	if( counter != V )mincost = min(mincost,coef+input[i].cost+((i==j)?0:input[j].cost));
      }
    }
    cout << mincost << endl;

    delete [] input;
  }
  return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 1224
final_rank: 18

code_snippet: #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <string>
#include <complex>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <sstream>
#include <numeric>
#include <functional>
#include <bitset>
#include <iomanip>
 
using namespace std;
 
 
#define INF (1<<29)
 
// math
#define Sq(x) ((x)*(x))
 
// container utility
#define ALL(x) (x).begin(), (x).end()
#define MP make_pair
#define PB push_back
#define EACH(it,c) for(__typeof((c).begin())it=(c).begin();it!=(c).end();it++)
 
// rep
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
 
// debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
 
// typedef
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VII;
typedef vector<VI> VVI;
 
typedef long long ll;
 
// conversion
template<class T> inline string toStr(T a) { ostringstream oss; oss << a; return oss.str(); }
inline int toInt(string s) { return atoi(s.c_str()); }
 
// prime
bool isPrime(int a) { for(int i=2; i*i <=a; i++) if(a%i == 0) return false; return true; }
 
// !!! set MAX_L number !!!
#define MAX_L (1000001)
#define MAX_SQRT_B ((int)sqrt(INT_MAX)+1)
  
bool is_prime[MAX_L];
vector<bool> is_prime_small(MAX_SQRT_B);
  
void segment_sieve(ll a, ll b) {
    
  for(int i=0; (ll)i*i < b; i++) is_prime_small[i] = true;
  for(int i=0; i < b-a; i++) is_prime[i] = true;
    
  if(a == 1) {
    is_prime[0] = false;
  }
    
  is_prime_small[0] = is_prime_small[1] = false;
    
  for(int i=2; (ll)i*i<b; i++) {
    if(is_prime_small[i]) {
      for(int j=2*i; (ll)j*j<b; j+=i) is_prime_small[j] = false;
      for(ll j = max(2LL, (a+i-1)/i)*i; j<b; j+=i) is_prime[j-a] = false;
    }
  }
}
 
//////////////////////////////////////////////////////////////
 
 
struct Edge {
  int to, cost, id;
  Edge(int t, int c, int i)
    : to(t), cost(c), id(i) {}
};
 
#define MAX_E (99)
 
vector<Edge> es[MAX_E];
int N, M;
 
bool isConnected(int x) {
   
  vector<bool> used(N);
  vector<int> VEC;
  VEC.PB(0); used[0] = 1;
   
  int v = 0;
  while(!VEC.empty()) {
    vector<int> NEXT;
     
    EACH(i, VEC) {
      EACH(e, es[*i]) {
    if(e->id != x && !used[e->to]) {
      used[e->to] = 1;
      NEXT.PB(e->to);
    }
      }
      v ++;
    }
    VEC = NEXT;
  }
  return N == v;
}
 
int main() {
   
  while( cin >> N >> M && (N|M) ) {
    for(int i=0; i<MAX_E; i++) {
      es[i].clear();
    }
     
    int base = 0;
    int id = 0;
     
    vector<int> cost;
     
    for(int i=0; i<M; i++) {
      int s, t, c;
      cin >> s >> t >> c;
       
      if(c <= 0) base += c;
      else {
    es[s].PB(Edge(t, c, id));
    es[t].PB(Edge(s, c, id));
    cost.PB(c);
    id ++;
      }
    }
     
    int E = id;
    int ans = INF;
     
    if(!isConnected(-1)) ans = 0;
     
    for(int i=0; i<E; i++) {
      if(!isConnected(i)) ans = min(ans, cost[i]);
    }
     
    for(int i=0; i<E-1; i++)
      for(int j=i+1; j<E; j++)
    ans = min(ans, cost[i]+cost[j]);
     
    cout << base + ans << endl;
  }
   
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1244
final_rank: 2

code_snippet: #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <string>
#include <complex>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <sstream>
#include <numeric>
#include <functional>
#include <bitset>
#include <iomanip>
 
using namespace std;
 
 
#define INF (1<<29)
 
// math
#define Sq(x) ((x)*(x))
 
// container utility
#define ALL(x) (x).begin(), (x).end()
#define MP make_pair
#define PB push_back
#define EACH(it,c) for(__typeof((c).begin())it=(c).begin();it!=(c).end();it++)
 
// rep
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
 
// debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
 
// typedef
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VII;
typedef vector<VI> VVI;
 
typedef long long ll;
 
// conversion
template<class T> inline string toStr(T a) { ostringstream oss; oss << a; return oss.str(); }
inline int toInt(string s) { return atoi(s.c_str()); }
 
// prime
bool isPrime(int a) { for(int i=2; i*i <=a; i++) if(a%i == 0) return false; return true; }
 
// !!! set MAX_L number !!!
#define MAX_L (1000001)
#define MAX_SQRT_B ((int)sqrt(INT_MAX)+1)
  
bool is_prime[MAX_L];
vector<bool> is_prime_small(MAX_SQRT_B);
  
void segment_sieve(ll a, ll b) {
    
  for(int i=0; (ll)i*i < b; i++) is_prime_small[i] = true;
  for(int i=0; i < b-a; i++) is_prime[i] = true;
    
  if(a == 1) {
    is_prime[0] = false;
  }
    
  is_prime_small[0] = is_prime_small[1] = false;
    
  for(int i=2; (ll)i*i<b; i++) {
    if(is_prime_small[i]) {
      for(int j=2*i; (ll)j*j<b; j+=i) is_prime_small[j] = false;
      for(ll j = max(2LL, (a+i-1)/i)*i; j<b; j+=i) is_prime[j-a] = false;
    }
  }
}
 
//////////////////////////////////////////////////////////////
 
 
struct Edge {
  int to, cost, id;
  Edge(int t, int c, int i)
    : to(t), cost(c), id(i) {}
};
 
#define MAX_E (100)
 
vector<Edge> es[MAX_E];
int N, M;
 
bool isConnected(int x) {
   
  vector<bool> used(N);
  vector<int> VEC;
  VEC.PB(0); used[0] = 1;
   
  int v = 0;
  while(!VEC.empty()) {
    vector<int> NEXT;
     
    EACH(i, VEC) {
      EACH(e, es[*i]) {
    if(e->id != x && !used[e->to]) {
      used[e->to] = 1;
      NEXT.PB(e->to);
    }
      }
      v ++;
    }
    VEC = NEXT;
  }
  return N == v;
}
 
int main() {
   
  while( cin >> N >> M && (N|M) ) {
    for(int i=0; i<MAX_E; i++) {
      es[i].clear();
    }
     
    int base = 0;
    int id = 0;
     
    vector<int> cost;
     
    for(int i=0; i<M; i++) {
      int s, t, c;
      cin >> s >> t >> c;
       
      if(c <= 0) base += c;
      else {
    es[s].PB(Edge(t, c, id));
    es[t].PB(Edge(s, c, id));
    cost.PB(c);
    id ++;
      }
    }
     
    int E = id;
    int ans = INF;
     
    if(!isConnected(-1)) ans = 0;
     
    for(int i=0; i<E; i++) {
      if(!isConnected(i)) ans = min(ans, cost[i]);
    }
     
    for(int i=0; i<E-1; i++)
      for(int j=i+1; j<E; j++)
    ans = min(ans, cost[i]+cost[j]);
     
    cout << base + ans << endl;
  }
   
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1244
final_rank: 2

code_snippet: #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <string>
#include <complex>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <sstream>
#include <numeric>
#include <functional>
#include <bitset>
#include <iomanip>
 
using namespace std;
 
 
#define INF (1<<29)
 
// math
#define Sq(x) ((x)*(x))
 
// container utility
#define ALL(x) (x).begin(), (x).end()
#define MP make_pair
#define PB push_back
#define EACH(it,c) for(__typeof((c).begin())it=(c).begin();it!=(c).end();it++)
 
// rep
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)
 
// debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;
 
// typedef
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VII;
typedef vector<VI> VVI;
 
typedef long long ll;
 
// conversion
template<class T> inline string toStr(T a) { ostringstream oss; oss << a; return oss.str(); }
inline int toInt(string s) { return atoi(s.c_str()); }
 
// prime
bool isPrime(int a) { for(int i=2; i*i <=a; i++) if(a%i == 0) return false; return true; }
 
// !!! set MAX_L number !!!
#define MAX_L (1000001)
#define MAX_SQRT_B ((int)sqrt(INT_MAX)+1)
  
bool is_prime[MAX_L];
vector<bool> is_prime_small(MAX_SQRT_B);
  
void segment_sieve(ll a, ll b) {
    
  for(int i=0; (ll)i*i < b; i++) is_prime_small[i] = true;
  for(int i=0; i < b-a; i++) is_prime[i] = true;
    
  if(a == 1) {
    is_prime[0] = false;
  }
    
  is_prime_small[0] = is_prime_small[1] = false;
    
  for(int i=2; (ll)i*i<b; i++) {
    if(is_prime_small[i]) {
      for(int j=2*i; (ll)j*j<b; j+=i) is_prime_small[j] = false;
      for(ll j = max(2LL, (a+i-1)/i)*i; j<b; j+=i) is_prime[j-a] = false;
    }
  }
}
 
//////////////////////////////////////////////////////////////
 
 
struct Edge {
  int to, cost, id;
  Edge(int t, int c, int i)
    : to(t), cost(c), id(i) {}
};
 
#define MAX_E (200)
 
vector<Edge> es[MAX_E];
int N, M;
 
bool isConnected(int x) {
   
  vector<bool> used(N);
  vector<int> VEC;
  VEC.PB(0); used[0] = 1;
   
  int v = 0;
  while(!VEC.empty()) {
    vector<int> NEXT;
     
    EACH(i, VEC) {
      EACH(e, es[*i]) {
    if(e->id != x && !used[e->to]) {
      used[e->to] = 1;
      NEXT.PB(e->to);
    }
      }
      v ++;
    }
    VEC = NEXT;
  }
  return N == v;
}
 
int main() {
   
  while( cin >> N >> M && (N|M) ) {
    for(int i=0; i<MAX_E; i++) {
      es[i].clear();
    }
     
    int base = 0;
    int id = 0;
     
    vector<int> cost;
     
    for(int i=0; i<M; i++) {
      int s, t, c;
      cin >> s >> t >> c;
       
      if(c <= 0) base += c;
      else {
    es[s].PB(Edge(t, c, id));
    es[t].PB(Edge(s, c, id));
    cost.PB(c);
    id ++;
      }
    }
     
    int E = id;
    int ans = INF;
     
    if(!isConnected(-1)) ans = 0;
     
    for(int i=0; i<E; i++) {
      if(!isConnected(i)) ans = min(ans, cost[i]);
    }
     
    for(int i=0; i<E-1; i++)
      for(int j=i+1; j<E; j++)
    ans = min(ans, cost[i]+cost[j]);
     
    cout << base + ans << endl;
  }
   
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1240
final_rank: 1

code_snippet: #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <climits>
#include <cstring>
#include <cctype>
#include <algorithm>
#include <string>
#include <complex>
#include <list>
#include <vector>
#include <stack>
#include <queue>
#include <deque>
#include <set>
#include <map>
#include <sstream>
#include <numeric>
#include <functional>
#include <bitset>
#include <iomanip>

using namespace std;


#define INF (1<<29)

// math
#define Sq(x) ((x)*(x))

// container utility
#define ALL(x) (x).begin(), (x).end()
#define MP make_pair
#define PB push_back
#define EACH(it,c) for(__typeof((c).begin())it=(c).begin();it!=(c).end();it++)

// rep
#define REP(i,a,b) for(int i=a;i<b;i++)
#define rep(i,n) REP(i,0,n)

// debug
#define dump(x)  cerr << #x << " = " << (x) << endl;
#define debug(x) cerr << #x << " = " << (x) << " (L" << __LINE__ << ")" << " " << __FILE__ << endl;

// typedef
typedef pair<int, int> PII;
typedef vector<int> VI;
typedef vector<PII> VII;
typedef vector<VI> VVI;

typedef long long ll;

// conversion
template<class T> inline string toStr(T a) { ostringstream oss; oss << a; return oss.str(); }
inline int toInt(string s) { return atoi(s.c_str()); }

// prime
bool isPrime(int a) { for(int i=2; i*i <=a; i++) if(a%i == 0) return false; return true; }

// !!! set MAX_L number !!!
#define MAX_L (1000001)
#define MAX_SQRT_B ((int)sqrt(INT_MAX)+1)
 
bool is_prime[MAX_L];
vector<bool> is_prime_small(MAX_SQRT_B);
 
void segment_sieve(ll a, ll b) {
   
  for(int i=0; (ll)i*i < b; i++) is_prime_small[i] = true;
  for(int i=0; i < b-a; i++) is_prime[i] = true;
   
  if(a == 1) {
    is_prime[0] = false;
  }
   
  is_prime_small[0] = is_prime_small[1] = false;
   
  for(int i=2; (ll)i*i<b; i++) {
    if(is_prime_small[i]) {
      for(int j=2*i; (ll)j*j<b; j+=i) is_prime_small[j] = false;
      for(ll j = max(2LL, (a+i-1)/i)*i; j<b; j+=i) is_prime[j-a] = false;
    }
  }
}

//////////////////////////////////////////////////////////////


struct Edge {
  int to, cost, id;
  Edge(int t, int c, int i)
    : to(t), cost(c), id(i) {}
};

#define MAX_E (300)

vector<Edge> es[MAX_E];
int N, M;

bool isConnected(int x) {
  
  vector<bool> used(N);
  vector<int> VEC;
  VEC.PB(0); used[0] = 1;
  
  int v = 0;
  while(!VEC.empty()) {
    vector<int> NEXT;
    
    EACH(i, VEC) {
      EACH(e, es[*i]) {
	if(e->id != x && !used[e->to]) {
	  used[e->to] = 1;
	  NEXT.PB(e->to);
	}
      }
      v ++;
    }
    VEC = NEXT;
  }
  return N == v;
}

int main() {
  
  while( cin >> N >> M && (N|M) ) {
    for(int i=0; i<MAX_E; i++) {
      es[i].clear();
    }
    
    int base = 0;
    int id = 0;
    
    vector<int> cost;
    
    for(int i=0; i<M; i++) {
      int s, t, c;
      cin >> s >> t >> c;
      
      if(c <= 0) base += c;
      else {
	es[s].PB(Edge(t, c, id));
	es[t].PB(Edge(s, c, id));
	cost.PB(c);
	id ++;
      }
    }
    
    int E = id;
    int ans = INF;
    
    if(!isConnected(-1)) ans = 0;
    
    for(int i=0; i<E; i++) {
      if(!isConnected(i)) ans = min(ans, cost[i]);
    }
    
    for(int i=0; i<E-1; i++)
      for(int j=i+1; j<E; j++)
	ans = min(ans, cost[i]+cost[j]);
    
    cout << base + ans << endl;
  }
  
  return 0;
}
accuracy: 1
time_ms: 10
memory_kb: 1248
final_rank: 4