The first line of each test case contains two integers N (N ≤ 100) and M, indicating the number of cities and the number of roads. The M lines followed, each of them contains three numbers A, B, and C, indicating that there is a road from city A to city B, whose length is C. (1 ≤ A,B ≤ N, A ≠ B, 1 ≤ C ≤ 1000).
6 9 1 2 5 2 3 5 3 1 10 3 4 12 4 1 8 4 6 11 5 4 7 5 6 9 6 5 4 6 5 1 2 1 2 3 1 3 4 1 4 5 1 5 6 1
42 -1HintIn the first sample, there are two cycles, (1->2->3->1) and (6->5->4->6) whose length is 20 + 22 = 42.
//
#include <stdio.h>
#include <iostream>
#include <string.h>
#include <stdio.h>
using namespace std;
const int N=210;
const int inf=(1<<28);
int n,m;//点数1->n,边数
int match[N],lack,w[N][N],lx[N],ly[N];;
bool visx[N],visy[N];
bool dfs(int x){
visx[x]=true;
for(int y=1; y<=n; y++){
if(visy[y]) continue;
int t=lx[x]+ly[y]-w[x][y];
if(t==0){
visy[y]=true;
if(match[y]==-1||dfs(match[y])){
match[y]=x;
return true;
}
}
else if(lack>t) lack=t;
}
return false;
}
int KM(){
int i,j;
for(i=0;i<=n;i++)lx[i]=-inf;//important
for(i=0;i<=n;i++)ly[i]=0;
memset(match,-1,sizeof(match));
for(i=1; i<=n; i++)for( j=1; j<=n; j++)if(w[i][j]>lx[i]) lx[i]=w[i][j];
for(int x=1; x<=n; x++){
while(1){
memset(visx,0,sizeof(visx));
memset(visy,0,sizeof(visy));
lack=inf;
if(dfs(x)) break;
for(i=1; i<=n; i++){
if(visx[i]) lx[i]-=lack;
if(visy[i]) ly[i]+=lack;
}
}
}
int total=0;
for(i=1;i<=n;i++)
{
total+=w[match[i]][i];
}
return total;
}
int main()
{
while(scanf("%d%d",&n,&m)==2)
{
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) w[i][j]=inf;
for(int i=0;i<m;i++)
{
int u,v,val;scanf("%d%d%d",&u,&v,&val);
w[u][v]=min(w[u][v],val);
}
for(int i=1;i<=n;i++) for(int j=1;j<=n;j++) w[i][j]=-w[i][j];
int ans=KM();
int flag=1;
for(int i=1;i<=n;i++)
{
if(match[i]==-1||w[match[i]][i]==-inf)//important
{
flag=0;break;
}
}
if(!flag) printf("-1\n");
else printf("%d\n",-ans);//important
}
return 0;
}