要想限制流量,总要想着拆点。
#include <iostream>
#include <cstring>
#include <cstdio>
#include <queue>
using namespace std;
int n, m, ss, tt, uu, vv, ww, maxFlow, minCost, cnt, hea[405], pre[405];
int dis[405];
const int oo=0x3f3f3f3f;
queue<int> d;
bool vis[405];
struct Edge{
int too, nxt, val, cst;
}edge[50005];
void add_edge(int fro, int too, int val, int cst){
edge[cnt].nxt = hea[fro];
edge[cnt].too = too;
edge[cnt].val = val;
edge[cnt].cst = cst;
hea[fro] = cnt++;
}
void addEdge(int fro, int too, int val, int cst){
add_edge(fro, too, val, cst);
add_edge(too, fro, 0, -cst);
}
bool bfs(){
memset(pre, -1, sizeof(pre));
memset(dis, 0x3f, sizeof(dis));
dis[ss] = 0;
d.push(ss);
vis[ss] = true;
while(!d.empty()){
int x=d.front();
d.pop();
vis[x] = false;
for(int i=hea[x]; i!=-1; i=edge[i].nxt){
int t=edge[i].too;
if(dis[t]>dis[x]+edge[i].cst && edge[i].val>0){
pre[t] = i;
dis[t] = dis[x] + edge[i].cst;
if(!vis[t]){
vis[t] = true;
d.push(t);
}
}
}
}
return dis[tt]!=oo;
}
void dinic(){
while(bfs()){
int tmp=oo;
for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too])
tmp = min(tmp, edge[i].val);
for(int i=pre[tt]; i!=-1; i=pre[edge[i^1].too]){
edge[i].val -= tmp;
edge[i^1].val += tmp;
minCost += tmp * edge[i].cst;
}
maxFlow += tmp;
}
}
int main(){
memset(hea, -1, sizeof(hea));
cin>>n>>m;
ss = 1; tt = n * 2;
for(int i=1; i<=n; i++)
if(i!=1 && i!=n) addEdge(i, i+n, 1, 0);
else addEdge(i, i+n, oo, 0);
for(int i=1; i<=m; i++){
scanf("%d %d %d", &uu, &vv, &ww);
addEdge(uu+n, vv, 1, ww);
}
dinic();
cout<<maxFlow<<" "<<minCost<<endl;
return 0;
}