杂题 [USACO4.2]草地排水

就是网络流的版题详情请看

https://www.cnblogs.com/qmcp/p/9686202.html

代码如下:

  1 #include<cstdio>
  2 #include<cmath>
  3 #include<algorithm>
  4 #include<cstring>
  5 #include<queue>
  6 using namespace std;
  7 typedef long long ll;
  8 const ll maxn = 1e5 + 7;
  9 const ll inf = 0x7777777;
 10 ll read()
 11 {
 12     ll a = 0,b = 1;
 13     char c = getchar();
 14     while(c < '0' or c > '9')
 15     {
 16         if(c == '-') b = -1;
 17         c = getchar();
 18     }
 19     while(c >= '0' and c <= '9')
 20     {
 21         a = a * 10 + c - '0';
 22         c = getchar();
 23         
 24     }return a * b;
 25 }
 26 ll head[maxn],dep[maxn],cnt = -1,n,m,s,t,ans;
 27 queue<ll>qq;
 28 struct node
 29 {
 30     ll w,to,nxt;
 31 }e[maxn];
 32 void add(ll a1,ll b1, ll c1)
 33 {
 34     e[++cnt].to = b1;
 35     e[cnt].nxt = head[a1];
 36     e[cnt].w = c1;
 37     head[a1] = cnt;
 38 }
 39 bool bfs()
 40 {
 41     while(!qq.empty()) qq.pop();
 42     memset(dep,0,sizeof(dep));
 43     qq.push(s);
 44     dep[s] = 1;
 45     while(!qq.empty())
 46     {
 47         ll u = qq.front();
 48         qq.pop();
 49         for(int i=head[u]; ~i; i=e[i].nxt)
 50         {
 51             if(dep[e[i].to] == 0 and e[i].w)
 52             {
 53                 dep[e[i].to] = dep[u] + 1;    
 54                 qq.push(e[i].to);
 55             }
 56         }
 57     }
 58     return dep[t];
 59 }
 60 ll dfs(ll u, ll limit)
 61 {
 62     if(limit == 0) return 0;
 63     if(u == t)
 64     {
 65         return limit;
 66     }
 67     for(int i=head[u]; ~i; i=e[i].nxt)
 68     {
 69         if(e[i].w and dep[e[i].to] == dep[u] + 1)
 70         {
 71             ll k = dfs(e[i].to, min(limit,e[i].w));
 72             if(k)
 73             {
 74                 e[i].w -= k;
 75                 e[i^1].w += k;
 76                 return k ;
 77             }
 78             
 79         }
 80     }
 81     return 0;
 82 }
 83 int main()
 84 {
 85     m = read(); n = read();
 86     s = 1; t = n;
 87     memset(head,-1,sizeof(head));
 88     for(int i=1; i<=m; i++)
 89     {
 90         ll p,q,z;
 91         p = read();
 92         q = read();
 93         z = read();
 94         add(p,q,z);
 95         add(q,p,0);
 96     }
 97     while(bfs()) {
 98         ll l = dfs(s,inf);
 99         if(l)
100         ans+=l;
101     }
102     printf("%lld",ans);
103     return 0;
104 }
原文地址:https://www.cnblogs.com/qmcp/p/9686217.html