跳到正文

剪贴板

剪贴板 j8a9m1j3

原文
剪贴板信息

剪贴板信息

收录
更新

P3381 【模板】最小费用最大流 Dinic模板

C++
#include<bits/stdc++.h>
#define int long long
using namespace std;
const int inf=1<<30,N=5e4+10,M=3e5+10;
struct node{
	int next,to,flow,cost;  //flow是边的残量 cost是单位费用
}edge[M];
int n,m,s,t,head[N],cur[N],tot=1,d[N];  //tot从1开始
int pre[N],dist[N];
bool vis[N];
int maxflow,mincost;
void add(int from,int to,int flow,int cost)
{
	edge[++tot].to=to,edge[tot].flow=flow,edge[tot].next=head[from],edge[tot].cost=cost,head[from]=tot;
	edge[++tot].to=from,edge[tot].flow=0,edge[tot].next=head[to],edge[tot].cost=-cost,head[to]=tot;
}
bool spfa()
{
	memset(vis,0,sizeof(vis));
	memset(dist,0x3f,sizeof(dist));
	memset(pre,0,sizeof(pre));
	queue<int>que;
	vis[s]=1;que.push(s);dist[s]=0;
	while(que.size())
	{
		int x=que.front();que.pop();
		vis[x]=0;
		for(int i=head[x];i;i=edge[i].next)
		{
			int y=edge[i].to,w=edge[i].cost;
			if(edge[i].flow>0&&dist[y]>dist[x]+w)
			{
				dist[y]=dist[x]+w;
				pre[y]=i;
				if(vis[y]==0)
				{
					que.push(y);
					vis[y]=1;
				}
			}
		}
	}
	return pre[t]!=0;
}
int dfs(int x,int flow)
{
	if(x==t)return flow;
	vis[x]=1;
	int rest=flow;
	for(int i=cur[x];i&&rest;i=edge[i].next)
	{
		cur[x]=i;
		int y=edge[i].to;
		if(vis[y]==0&&edge[i].flow>0&&dist[y]==dist[x]+edge[i].cost)
		{
			int k=dfs(y,min(rest,edge[i].flow));
			rest-=k;
			edge[i].flow-=k;
			edge[i^1].flow+=k;
			mincost+=edge[i].cost*k;
		}
	}
	vis[x]=0;
	return flow-rest;
}
void dinic()
{
	while(spfa())
	{
		memcpy(cur,head,sizeof(head));
		maxflow+=dfs(s,inf);
	}
}
signed main()
{
	ios::sync_with_stdio(false);
	cin>>n>>m>>s>>t;
	while(m--)
	{
		int u,v,w,c;
		cin>>u>>v>>w>>c;
		add(u,v,w,c);
	}
	dinic();
	cout<<maxflow<<" "<<mincost;

	return 0;
}