Calculate the number of non-adjacent pairs in the n * m board to maximize the sum.
Question: black and white dyeing Based on chess. The capacity from the source point to the Black Point is a number, the capacity from the Black Point to the surrounding white point is infinite, and the capacity from the white point to the sink point is a number, the final answer is the total value minus the minimum cut (from the Internet ).
[Cpp]
# Include <stdio. h>
# Include <stdlib. h>
# Include <string. h>
# Include <string>
# Include <queue>
# Include <algorithm>
# Include <vector>
# Include <stack>
# Include <list>
# Include <iostream>
# Include <map>
Using namespace std;
# Define inf 0x7f3f3f
# Deprecision Max 50000
Int max (int a, int B)
{
Return a> B? A: B;
}
Int min (int a, int B)
{
Return a <B? A: B;
}
Int dis [Max], gap [Max], pre [Max], cur [Max], p [Max], sum;
Int d [4] [2] = {, 0,-1 };
Int mp [220] [220];
Int n, m, s, t, eid;
Struct node
{
Int to, next, c;
} E [8 * Max];
Void addedge (int u, int v, int c)
{
E [eid]. to = v;
E [eid]. c = c;
E [eid]. next = p [u];
P [u] = eid ++;
}
Void ISAP (int st, int ed, int n, int count) // start point, end point, number of vertices
{
Memset (dis, 0, sizeof (dis ));
Memset (gap, 0, sizeof (gap); gap [0] = n;
Memcpy (cur, p, sizeof (p); // memcpy!
Int I, flag, v, u = pre [st] = st, maxflow = 0, aug = inf; // puts ("akk ");
While (dis [st] <n)
{
For (flag = 0, I = cur [u]; I! =-1; I = e [I]. next) // cur [u]
If (e [I]. c & dis [u] = dis [e [I]. to] + 1)
{
Flag = 1;
Break;
}
If (flag)
{
If (aug> e [I]. c)
Aug = e [I]. c;
V = e [I].;
Pre [v] = u;
Cur [u] = I;
U = v;
If (u = ed)
{
For (u = pre [u]; 1; u = pre [u]) // notice!
{
E [cur [u]. c-= aug;
E [cur [u] ^ 1]. c + = aug;
If (u = st) break;
// Puts ("akkk ");
}
Maxflow + = aug;
Aug = inf;
}
}
Else
{
Int minx = n;
For (I = p [u]; I! =-1; I = e [I]. next)
If (e [I]. c & dis [e [I]. to] <minx)
{
Minx = dis [e [I]. to];
Cur [u] = I;
}
If (-- gap [dis [u] = 0)
Break;
Dis [u] = minx + 1;
Gap [dis [u] ++;
U = pre [u];
}
}
// Printf ("Case % d: \ n % d \ n", count, maxflow );
Printf ("% d \ n", sum-maxflow );
}
Int main ()
{
Int m, n, t, count = 1;
Int u, v, c, I, j, k, x, y;
While (scanf ("% d", & n, & m )! = EOF)
{
Eid = 0;
Memset (p,-1, sizeof (p ));
Sum = 0;
For (I = 0; I <n; I ++)
For (j = 0; j <m; j ++)
{
Scanf ("% d", & mp [I] [j]);
Sum + = mp [I] [j];
}
For (I = 0; I <n; I ++)
For (j = 0; j <m; j ++)
{
If (I + j) % 2 = 0)
{
Addedge (n * m, I * m + j, mp [I] [j]);
Addedge (I * m + j, n * m, 0 );
For (k = 0; k <4; k ++)
{
X = I + d [k] [0];
Y = j + d [k] [1];
If (x> = 0 & y> = 0 & x <n & y <m)
{
Addedge (I * m + j, x * m + y, inf );
Addedge (x * m + y, I * m + j, 0 );
}
}
}
Else
{
Addedge (I * m + j, n * m + 1, mp [I] [j]);
Addedge (n * m + 1, I * m + j, 0 );
}
}
// Printf ("% d \ n", eid );
ISAP (n * m, n * m + 1, n * m + 2, count ++ );
// Printf ("% d \ n ")
}
}