#include<cstdio>
#include<algorithm>
#include<cstring>
#include<cmath>
#include<queue>
using namespace std;
const int inf=0x3f3f3f3f;
struct aa
{
int to,pre,cap,flow;
}edge[100009];
int dis[10009],head[100009],cur[100009],tot;
int n,m;
void addedge(int x,int y,int z)
{
edge[++tot].to=y;edge[tot].pre=head[x];head[x]=tot;edge[tot].cap=z;
}
bool bfs()
{
memset(dis,0,sizeof(dis));
queue<int> q;
q.push(1);dis[1]=1;//注意这里赋值为1
while (!q.empty())
{
int u=q.front();q.pop();
for (int i=head[u];i;i=edge[i].pre)
if (edge[i].cap>edge[i].flow&&!dis[edge[i].to])
{
int v=edge[i].to;
dis[v]=dis[u]+1;
q.push(v);
if (v==n) return true;
}
}
return false;
}
int dfs(int u,int maxflow)
{
if (u==n||maxflow==0) return maxflow;
int &i=cur[u],ans=0;
for (;i;i=edge[i].pre)
if (dis[edge[i].to]==dis[u]+1)
{
int flow=dfs(edge[i].to,min(edge[i].cap-edge[i].flow,maxflow));
if (flow==0) continue;
ans+=flow;
maxflow-=flow;
edge[i].flow+=flow;
edge[(i-1)^1+1].flow-=flow;
if (maxflow==0) return ans;
}
return ans;
}
int work()
{
int ans=0;
while (bfs())
{
for (int i=1;i<=n;i++) cur[i]=head[i];
ans+=dfs(1,inf);
}
return ans;
}
int main()
{
scanf("%d%d",&m,&n);
int x,y,z;
for (int i=1;i<=m;i++)
{
scanf("%d%d%d",&x,&y,&z);
addedge(x,y,z);addedge(y,x,0);
}
printf("%d",work());
return 0;
}
dinic模板
最新推荐文章于 2019-11-29 21:59:53 发布