题目:戳我呀
题解:网络流最大流模板题,想了解网络流模板可以去这里学习一下
代码:
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<set>
#include<queue>
#include<vector>
#include<stack>
#define INF 0x3f3f3f3f
#define N 205
#define M 205
#define LL long long
using namespace std;
int n,m,c;
int head[N],cur[N],deep[N];
struct ljh
{
int to,next;
LL w;
}e[2*M];
inline void add(int x,int y,LL z)
{
e[c].next=head[x];
e[c].w=z;
e[c].to=y;
head[x]=c++;
}
bool bfs(int s,int t)
{
memset(deep,0,sizeof(deep));
deep[s]=1;
queue<int>q;
q.push(s);
while(!q.empty())
{
int now=q.front();
q.pop();
for(int i=head[now];i!=-1;i=e[i].next)
{
int nex=e[i].to;
if(deep[nex]==0&&e[i].w>0)
{
deep[nex]=deep[now]+1;
q.push(nex);
}
}
}
return deep[t];
}
LL dfs(int x,int t,LL maxflow)
{
if(x==t)return maxflow;
LL ans=0;
for(int i=head[x];i!=-1;i=e[i].next)
{
int nex=e[i].to;
if(deep[nex]!=deep[x]+1||e[i].w<=0||ans>=maxflow)continue;
cur[x]=i;
LL k=dfs(nex,t,min(e[i].w,maxflow-ans));
e[i].w-=k;
e[i^1].w+=k;
ans+=k;
}
if(ans==0)deep[x]=-2;//炸点优化
return ans;
}
LL Dinic(int s,int t)
{
LL ans=0;
while(bfs(s,t))
{
memcpy(cur,head,sizeof(head));
ans+=dfs(s,t,INF);
}
return ans;
}
int main()
{
while(~scanf("%d%d",&m,&n))
{
c=0;
memset(head,-1,sizeof(head));
for(int i=1;i<=m;i++)
{
int x,y;
LL z;
scanf("%d%d%lld",&x,&y,&z);
add(x,y,z);
add(y,x,0);
}
printf("%lld\n",Dinic(1,n));
}
}
/*
5 4
1 2 40
1 4 20
2 4 20
2 3 30
3 4 10
6 5
1 2 4
2 4 3
4 5 5
3 5 4
2 3 2
1 3 6
*/