BZOJ1001 狼抓兔子

最小割

代码

# include <bits/stdc++.h>
# define IL inline
# define RG register
# define Fill(a, b) memset(a, b, sizeof(a))
# define Copy(a, b) memcpy(a, b, sizeof(a))
using namespace std;
typedef long long ll;
const int _(1e6 + 10), __(1e7 + 10);

IL ll Read(){
    RG char c = getchar(); RG ll x = 0, z = 1;
    for(; c < '0' || c > '9'; c = getchar()) z = c == '-' ? -1 : 1;
    for(; c >= '0' && c <= '9'; c = getchar()) x = (x << 1) + (x << 3) + (c ^ 48);
    return x * z;
}

int n, m, fst[_], nxt[__], to[__], cnt, S, T, lev[_], Q[_], max_flow, w[__];
int nn[1010][1010], tt;

IL void Add(RG int u, RG int v, RG int f){
    w[cnt] = f; to[cnt] = v; nxt[cnt] = fst[u]; fst[u] = cnt++;
    //w[cnt] = 0; to[cnt] = u; nxt[cnt] = fst[v]; fst[v] = cnt++;
}

int Dfs(RG int u, RG int maxf){
    if(u == T) return maxf;
    RG int ret = 0;
    for(RG int e = fst[u]; e != -1; e = nxt[e]){
        if(lev[to[e]] != lev[u] + 1 || !w[e]) continue;
        RG int f = Dfs(to[e], min(w[e], maxf - ret));
        ret += f; w[e ^ 1] += f; w[e] -= f;
        if(ret == maxf) break;
    }
    if(!ret) lev[u] = 0;
    return ret;
}

IL bool Bfs(){
    RG int h, t = 1; Q[h = 0] = S; Fill(lev, 0); lev[S] = 1;
    while(h < t){
        RG int u = Q[h++];
        for(RG int e = fst[u]; e != -1; e = nxt[e]){
            if(lev[to[e]] || !w[e]) continue;
            lev[to[e]] = lev[u] + 1;
            Q[t++] = to[e];
        }
    }
    return lev[T];
}

int main(){
    n = Read(); m = Read();
    for(RG int i = 1; i <= n; ++i)
        for(RG int j = 1; j <= m; ++j)
          nn[i][j] = ++tt, fst[nn[i][j]] = -1;
    S = 1; T = n * m; RG int a;
    for(RG int i = 1; i <= n; ++i)
        for(RG int j = 1; j < m; ++j)
            a = Read(), Add(nn[i][j], nn[i][j + 1], a), Add(nn[i][j + 1], nn[i][j], a);
    for(RG int i = 1; i < n; ++i)
        for(RG int j = 1; j <= m; ++j)
            a = Read(), Add(nn[i][j], nn[i + 1][j], a), Add(nn[i + 1][j], nn[i][j], a);
    for(RG int i = 1; i < n; ++i)
        for(RG int j = 1; j < m; ++j)
            a = Read(), Add(nn[i][j], nn[i + 1][j + 1], a), Add(nn[i + 1][j + 1], nn[i][j], a);
    while(Bfs()) max_flow += Dfs(S, 0x7fffffff);
    printf("%d\n", max_flow);
    return 0;
}

posted @ 2017-12-28 19:36  Cyhlnj  阅读(153)  评论(0编辑  收藏  举报