https://blog.csdn.net/qq_39809664/article/details/79109811
- https://blog.csdn.net/qq_40772692/article/details/83041282
- https://www.cnblogs.com/gtarcoder/p/4890739.html
#include <iostream>
#include<bits/stdc++.h>
using namespace std;
#define INF 0x3f3f3f3f
const int maxn = 5000 + 7;
/**********邻接表数组形式***********/
struct Edge{/***表边**/
int from,to;/****起点终点***/
int next;/*****相同起点 的下一条边***/
int cap,flow;/*****该边 的 容量 和流量***/
int cost;/****花费**/
}edge[maxn*20];
int head[maxn];/****表头***/
int pre[maxn];
int dist[maxn],n,m,tot,s,t;
bool vis[maxn];
/***加边函数********/
void addEdge(int a,int b,int c,int cost){//注意反向弧的负权值
edge[tot].from = a;edge[tot].to = b;/*****a到 b****/
edge[tot].next = head[a];/*****他的下一条边 是 之前最后一条 以 a为起点的边******/
edge[tot].cap = c;edge[tot].flow = 0;/*******容量 流量 流量初始化 为 0*******/
edge[tot].cost = cost;head[a] = tot++;/***他成为 目前 以a 为起点的最后一条边****/
/*****反向边的建立 反向边的容量 初始化为 0******/
edge[tot].from = b;edge[tot].to = a;edge[tot].next = head[b];edge[tot].cap = 0;edge[tot].flow = 0;edge[tot].cost = -cost;head[b] = tot++;
}
bool SPFA(){//SPFA求增广路,dist[t]保存最小花费 ,
memset(dist,INF,sizeof(dist));
memset(vis,0,sizeof(vis));
queue<int> que;
dist[s] = 0;
vis[s] = 1;
que.push(s);
while(!que.empty()){
int u = que.front();
que.pop();
vis[u] = 0;
for(int i = head[u];i!= -1/**可以 用~i*/;i = edge[i].next){
int v = edge[i].to;
if(edge[i].cap > edge[i].flow && dist[v] > dist[u] + edge[i].cost){
dist[v] = dist[u] + edge[i].cost;
pre[v] = i;
if(!vis[v]){
vis[v] = 1;
que.push(v);
}
}
}
}
if(dist[t]!=INF)return true;
return false;
}
int CostFlow(int &flow){//EK算法
int mincost = 0;
while(SPFA()){//能找到增广路
int Min = INF;
for(int i = t;i!=s;i = edge[pre[i]].from)
{//寻找最小流
Min = min(Min,edge[pre[i]].cap - edge[pre[i]].flow);
}
for(int i = t;i!=s;i = edge[pre[i]].from){//处理所有边
edge[pre[i]].flow+=Min;
edge[pre[i]^1].flow-=Min;
}
flow+=Min;
mincost+=(dist[t]*Min);//累和最小花费
}
return mincost;
}
int main()
{
int T;
scanf("%d",&T);
while(T--){
tot = 0;
memset(head,-1,sizeof(head));
scanf("%d%d%d%d",&n,&m,&s,&t);
for(int i = 0;i<m;i++){
int a,b,c,cost;
scanf("%d%d%d%d",&a,&b,&c,&cost);
addEdge(a,b,c,cost);
}
int MaxFlow = 0;
int MinCost = CostFlow(MaxFlow);
printf("%d %d\n",MaxFlow,MinCost);
}
return 0;
}