/**
题目:UVA1658 Admiral
链接:https://vjudge.net/problem/UVA-1658
题意:lrj入门经典P375
求从s到t的两条不相交(除了s和t外,没有公共点)的路径,使得权值和最小。 思路:拆点法。
除了s,t外。把其他点都拆成两个。 例如点A,拆成A和A'。A指向A'连一条容量为1,花费为0的边。
原来指向A的,仍然指向A点。
原来A指向其他点的,由A'指向它们。 最小费用最大流求流量为2时候的最小费用即可。 */
#include<iostream>
#include<cstring>
#include<vector>
#include<map>
#include<cstdio>
#include<algorithm>
#include<queue>
using namespace std;
const int INF = 0x3f3f3f3f;
typedef long long LL;
const int N = ;
struct Edge{
int from, to, cap, flow, cost;
Edge(int u,int v,int c,int f,int w):from(u),to(v),cap(c),flow(f),cost(w){}
};
struct MCMF{
int n, m;
vector<Edge> edges;
vector<int> G[N];
int inq[N];
int d[N];
int p[N];
int a[N]; void init(int n){
this->n = n;
for(int i = ; i <= n; i++) G[i].clear();
edges.clear();
} void AddEdge(int from,int to,int cap,long long cost){
edges.push_back(Edge(from,to,cap,,cost));
edges.push_back(Edge(to,from,,,-cost));
m = edges.size();
G[from].push_back(m-);
G[to].push_back(m-);
} bool BellmanFord(int s,int t,int &flow,long long &cost){
for(int i = ; i <= n; i++) d[i] = INF;
memset(inq, , sizeof inq);
d[s] = ; inq[s] = ; p[s] = ; a[s] = INF; queue<int> Q;
Q.push(s);
while(!Q.empty()){
int u = Q.front(); Q.pop();
inq[u] = ;
for(int i = ; i < G[u].size(); i++){
Edge& e = edges[G[u][i]];
if(e.cap>e.flow&&d[e.to]>d[u]+e.cost){
d[e.to] = d[u]+e.cost;
p[e.to] = G[u][i];
a[e.to] = min(a[u],e.cap-e.flow);
if(!inq[e.to]) {Q.push(e.to); inq[e.to] = ;}
}
}
}
if(d[t]==INF) return false;
flow += a[t];
cost += (long long)d[t]*(long long)a[t];
for(int u = t; u!=s; u = edges[p[u]].from){
edges[p[u]].flow+=a[t];
edges[p[u]^].flow-=a[t];
}
///流量为2时的最小费用。
if(flow==){
return false;
}
return true;
}
int MincostMaxflow(int s,int t,long long &cost){
int flow = ;
cost = ;
while(BellmanFord(s,t,flow,cost));
return flow;
}
};
vector<int>node[N];
int main()
{
int n, m;
while(scanf("%d%d",&n,&m)==)
{
int s = , t = n;
int u, v;
long long cost;
MCMF mcmf;
mcmf.init(n*);
for(int i = ; i <= n; i++) node[i].clear();
for(int i = ; i < m; i++){
scanf("%d%d%lld",&u,&v,&cost);
node[u].push_back(v);
node[u].push_back(cost);
}
int tot = n+;
for(int i = ; i < node[].size(); i+=){
mcmf.AddEdge(,node[][i],,node[][i+]);
}
for(int i = ; i < n; i++){///除了源点和汇点,其他拆点
int from = i, to = tot++;
mcmf.AddEdge(from,to,,);
for(int j = ; j < node[i].size(); j+=){
mcmf.AddEdge(to,node[i][j],,node[i][j+]);
}
}
for(int i = ; i < node[n].size(); i+=){
mcmf.AddEdge(n,node[n][i],,node[n][i+]);
}
mcmf.MincostMaxflow(s,t,cost);
printf("%lld\n",cost);
}
return ;
}