代码:
#include <cstdio>
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <queue>
#define ll long long
#define maxn 2200
#define maxm 301000
using namespace std;
const long long my_inf= 214743647;
struct WLL{
int now[maxn];
long long v[maxm];
int st[maxm],ed[maxm],pre[maxm],tot;
long long cost[maxm];
long long deep[ maxn ];
long long ans,sum;
int S,T;
void init(){
tot=1;
memset(now,0,sizeof(now));
}
void build(int a,int b,int c,int d){
pre[++tot]=now[a];
now[a]=tot;
st[tot]=a;
ed[tot]=b;
v[tot]=c;
cost[tot]=d;
}
void add_edge(int a,int b,int cost){
build(a,b,1,cost);
build(b,a,0,-cost);
}
deque<int> Q;
int last[maxn];
bool vis[maxn];
bool spfa(){
memset( deep , -1 , sizeof(deep) );
memset( vis , 0 ,sizeof( vis ) );
deep[S]=0;
Q.push_back(S);
while (!Q.empty())
{
int x=Q.front();
Q.pop_front();
for (int p=now[x];p;p=pre[p])
if (v[p])
if ( ( deep[ed[p]] <0 ) || ( deep[ ed[p] ] > deep[ x ]+cost[ p ] ) )
{
int y=ed[p];
deep[ y ]=deep[ x ]+cost[p];
last[ y ]= p;
if ( !vis[ ed[p] ] )
{
Q.push_back( ed[p] );
vis[ ed[p] ]=1;
}
}
vis[ x ]=0;
}
if ( deep[ T ]==-1 )
return 0;
long long Max=my_inf;
for (int x= T; x!=S ; x = st[ last[ x ] ] )
{
int p=last[ x ];
Max= min( Max , v[ p ] );
}
sum+=Max;
for (int x= T; x!=S ; x = st[ last[ x ] ] )
{
int p=last[ x ];
v[ p ] -= Max;
v[ p^1]+=Max;
ans+=Max*cost[ p ];
}
return 1;
}
void count(int &x,int &y){
sum=0; ans=0;///sum是最大流, ans是最小费用
while ( spfa() );
x=sum,y=ans;
}
}A;
int n,m;
void doit(){
A.init();
cin>>n>>m;
for (int i=1;i<=m;i++)
{
int a,b,c;
cin>>a>>b>>c;
A.add_edge(a,b,c);
A.add_edge(b,a,c);
}
A.S=n+1,A.T=n+2;
A.add_edge(A.S,1,0);
A.add_edge(A.S,1,0);
A.add_edge(n,A.T,0);
A.add_edge(n,A.T,0);
int sum,ans;
A.count(sum,ans);
if ( sum!=2 )
cout<<-1<<endl;
else
cout<<ans<<endl;
return ;
}
int main(){
ios::sync_with_stdio(0),cin.tie(0),cout.tie(0);
doit();
return 0;
}