LOJ - #117. 有源汇有上下界最小流(有源汇有上下界的最小流)

题目链接:点击查看

题目大意:给出一个 n 个点和 m 条边的有向图,每条边都有一个流量限制 [ lower , upper ],给定源点 s 和汇点 t ,求出源点到汇点的最小流

题目分析:参考我的上一篇博客:https://blog.csdn.net/qq_45458915/article/details/108339354

坑点就是卡常+卡当前弧优化,第八个点会TLE,如果有当前弧优化可以删除试一下,如果链式前向星是用结构体封装的可以解封装试一下

代码:

#include<iostream>
#include<cstdio>
#include<string>
#include<ctime>
#include<cmath>
#include<cstring>
#include<algorithm>
#include<stack>
#include<climits>
#include<queue>
#include<map>
#include<set>
#include<sstream>
#include<cassert>
#include<bitset>
#include<unordered_map>
using namespace std;

typedef long long LL;

typedef unsigned long long ull;

const int inf=0x3f3f3f3f;

const int N=50100;

const int M=125100;

int du[N];
 
int head[N],cnt,edge[(N+M)<<1],ver[(N+M)<<1],nt[(N+M)<<1];
 
void addedge(int u,int v,int w)
{
	ver[cnt]=v;
	edge[cnt]=w;
	nt[cnt]=head[u];
	head[u]=cnt++;
	ver[cnt]=u;
	edge[cnt]=0;//反向边边权设置为0
	nt[cnt]=head[v];
	head[v]=cnt++;
}
 
int d[N];//深度
 
bool bfs(int s,int t)//寻找增广路
{
	memset(d,0,sizeof(d));
	queue<int>q;
	q.push(s);
	d[s]=1;
	while(!q.empty())
	{
		int u=q.front();
		q.pop();
		for(int i=head[u];i!=-1;i=nt[i])
		{
			if(d[ver[i]])
				continue;
			if(!edge[i])
				continue;
			d[ver[i]]=d[u]+1;
			q.push(ver[i]);
			if(ver[i]==t)
				return true;
		}
	}
	return false;
}
 
int dinic(int x,int t,int flow)//更新答案
{
	if(x==t)
		return flow;
	int rest=flow,i;
	for(i=head[x];i!=-1&&rest;i=nt[i])
	{
		if(edge[i]&&d[ver[i]]==d[x]+1)
		{
			int k=dinic(ver[i],t,min(rest,edge[i]));
			if(!k)
				d[ver[i]]=0;
			edge[i]-=k;
			edge[i^1]+=k;
			rest-=k;
		}
	}
	return flow-rest;
}
 
void init()
{
	memset(head,-1,sizeof(head));
	cnt=0;
}
 
int solve(int st,int ed)
{
	int ans=0,flow;
	while(bfs(st,ed))
		while(flow=dinic(st,ed,inf))
			ans+=flow;
	return ans;
}

int main()
{
#ifndef ONLINE_JUDGE
//  freopen("data.in.txt","r",stdin);
//  freopen("data.out.txt","w",stdout);
#endif
//  ios::sync_with_stdio(false);
	init();
	int n,m,s,t;
	scanf("%d%d%d%d",&n,&m,&s,&t);
	while(m--)
	{
		int u,v,lower,upper;
		scanf("%d%d%d%d",&u,&v,&lower,&upper);
		addedge(u,v,upper-lower);
		du[u]-=lower,du[v]+=lower;
	}
	int st=N-1,ed=st-1,sum=0;
	for(int i=1;i<=n;i++)
	{
		if(du[i]>0)
		{
			addedge(st,i,du[i]);
			sum+=du[i];
		}
		else
			addedge(i,ed,-du[i]);
	}
	addedge(t,s,inf);
	if(solve(st,ed)!=sum)
	{
		puts("please go home to sleep");
		return 0;
	}
	int ans=edge[cnt-1];
	edge[cnt-1]=edge[cnt-2]=0;
	printf("%d\n",ans-solve(t,s));








   return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_45458915/article/details/108339622