#include<cmath>
#include<queue>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
using namespace std;
const int N=1e4+10,M=2e5+10,inf=0x3f3f3f3f;
int n,m,s,t;
int nxt[M],head[N],go[M],edge[M],cost[M],cur[N],tot=1;
inline void add(int u,int v,int o1,int o2){
nxt[++tot]=head[u],head[u]=tot,go[tot]=v,edge[tot]=o1,cost[tot]=o2;
nxt[++tot]=head[v],head[v]=tot,go[tot]=u,edge[tot]=0,cost[tot]=-o2;
}
int dis[N],ret;
bool vis[N];
struct node{
int u,d;
bool operator<(const node &rhs)const{
return d>rhs.d;
}
};
inline bool spfa(){
memset(dis,0x3f,sizeof(dis));
std::priority_queue<node>q;
q.push((node){s,0}),dis[s]=0;
while(q.size()){
int u=q.top().u;
int d=q.top().d;
q.pop();
if(d!=dis[u])continue;
for(int i=head[u];i;i=nxt[i]){
int v=go[i];
if(edge[i]&&dis[v]>dis[u]+cost[i]){
dis[v]=dis[u]+cost[i];
q.push((node){v,dis[v]});
}
}
}
return dis[t]!=inf;
}
int dinic(int u,int flow){
if(u==t)return flow;
vis[u]=1;
int rest=flow,k;
for(int i=head[u];i&&rest;i=nxt[i]){
int v=go[i];
if(!vis[v]&&edge[i]&&dis[v]==dis[u]+cost[i]){
k=dinic(v,min(edge[i],rest));
if(!k)dis[v]=-1;
else ret+=k*cost[i],edge[i]-=k,edge[i^1]+=k,rest-=k;
}
}
vis[u]=0;
return flow-rest;
}
signed main(){
scanf("%d%d%d%d", &n, &m, &s, &t);
int u, v, w, c;
while(m--){
scanf("%d%d%d%d", &u, &v, &w, &c);
add(u, v, w, c);
}
int flow=0,maxflow=0;
while(spfa())
while(flow=dinic(s,inf))maxflow+=flow;
cout<<maxflow<<' '<<ret<<endl;
}
原文地址:https://www.cnblogs.com/naruto-mzx/p/12204915.html
时间: 2024-11-12 06:04:11