某岛

… : "…アッカリ~ン . .. . " .. .
July 18, 2015

HDU 1569. 方格取数(2)

二分图最大独立集,最小割。

const int NN = int(1e2) + 9;
const int N = int(1e4) + 9, M = int(N*6) * 2;

//struct Network_Flow{

int D[N], hd[N], suc[M], to[M], cap[M];
int n, m, s, t;

inline void ae(int x, int y, int c){
    suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
    suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = 0;
}

inline void aee(int x, int y, int c){
    suc[m] = hd[x], hd[x] = m, to[m] = y, cap[m++] = c,
    suc[m] = hd[y], hd[y] = m, to[m] = x, cap[m++] = c;
}

#define v to[i]
#define c cap[i]
#define f cap[i^1]

LL sap(){
    LL z=0; static int cnt[N],cur[N],pre[N];
    fill(D,D+n,n),fill(cnt,cnt+n,0);cnt[n]=n;
    int u=s;cur[s]=hd[s];while (D[s]){
#define i cur[u]
        if (u==t){
            int d=INF;for(u=s;u!=t;u=v)checkMin(d,c);
            z+=d;for(u=s;u!=t;u=v)f+=d,c-=d;u=s;
        }
#undef i
        int i;for(i=cur[u];i;i=suc[i]){
            if(D[u]+1==D[v]&&c){cur[u]=i,cur[v]=hd[v],pre[v]=u,u=v;break;}
        }
        if (!i){
            if (!--cnt[D[u]])break;
            D[u]=1;REP_G(i,u)if(c)checkMax(D[u],D[v]);--D[u];
            ++cnt[D[u]];if(u==s)cur[u]=hd[u];else u=pre[u];
        }
    }

    return z;
}

#undef f
#undef c
#undef v

int r, c, tot;

int id(int i, int j){
    return i*c+j+1;
}

bool inGrid(int x, int y){
    return x >= 0 && y >= 0 && x < r && y < c;
}

void init(){
    s = 0, t = r*c+1, n = t+1, m = 2; fill(hd, hd+n, 0);
    tot = 0;

    REP_2(i, j, r, c){
        int cap; tot += RD(cap);
        if (i&1^j&1) ae(s, id(i,j), cap);
        else ae(id(i,j), t, cap);
    }

    REP_2(i, j, r, c) if (i&1^j&1) REP(d, 4){
        int x = i + dx[d], y = j + dy[d];
        if (inGrid(x, y)) ae(id(i,j),id(x,y),INF);
    }
}

//} G;



int main(){

#ifndef ONLINE_JUDGE
    freopen("in.txt", "r", stdin);
#endif

    while (~scanf("%d %d", &r, &c)){
        init(); OT(tot-sap());
    }
}