P2740 [USACO4.2]草地排水Drainage Ditches

题目

题目

思路

其实还是一道最大流板子,使用Dinic算法解决,注意输入顺序,不知道DINIC算法戳这里
code:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<string>
#include<cstring>
using namespace std;
int n,m,s,t,x,y,tot=2,head[201],dep[201],l,r,u[201],r2;
long long w,ans;
long long mn(long long x,long long y)
{
    
    
 return (x>y?y:x);
}
struct f{
    
    
 int to,net;
 long long w;
} a[10011];
void add(int x,int y,long long w)
{
    
    
 a[tot].to=y,a[tot].w=w,a[tot].net=head[x],head[x]=tot++;
 return;
}
bool bfs()
{
    
    
 memset(dep,0,sizeof(dep));
 l=0,r=0;
 u[r++]=s;
 dep[s]=1;
 while (l<r)
 {
    
    
  r2=r;
  for (int i=l;i<r;i++)
  {
    
    
   for (int j=head[u[i]];j;j=a[j].net)
   {
    
    
    if (a[j].w!=0&&dep[a[j].to]==0)
    {
    
    
     u[r2++]=a[j].to;
     dep[a[j].to]=dep[u[i]]+1;
    }
   }
  }
  l=r,r=r2;
 }
 return dep[t];
}
long long dfs(int d,long long in)
{
    
    
 if (d==t) return in;
 long long out=0;
 int uw=dep[d]+1;
 for (int j=head[d];j&&in;j=a[j].net)
 {
    
    
  if (a[j].w==0||dep[a[j].to]!=uw) continue;
  long long s=dfs(a[j].to,mn(in,a[j].w));
  out+=s,in-=s;
  a[j].w-=s,a[j^1].w+=s;
 }
 if (out==0)
 {
    
    
  dep[d]=0;
 }
 return out;
}
int main()
{
    
    
 scanf("%d%d",&m,&n);
 s=1,t=n;
 for (int i=0;i<m;i++)
 {
    
    
  scanf("%d%d%lld",&x,&y,&w);
  add(x,y,w);
  add(y,x,0);
 }
 while (bfs())
 {
    
    
  ans+=dfs(s,1e18);
 }
 cout<<ans;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_49843717/article/details/114333944
今日推荐