题意:一个n*m的网络,每个单元都有一块价值Cij的宝石,问最多能取多少价值的宝石且任意两块宝石不相邻。
经典的最大点权独立集问题,一个很巧妙的转化,转化为最小点权覆盖。
将网格黑白染色,从源点到每个黑点连一条边,从每个白点到汇点连一条边,容量均为宝石价值。每个黑色与周围四个白点连边,为inf,做一次最小割,即为最小点权覆盖,记为tmp,则ans = ∑Cij - tmp
代码:
#include<cstdio>
#include<cstring>
using namespace std;
const int inf = 0x3f3f3f3f;
const int maxn = 50 * 50 + 10;
const int maxm = 50000;
struct Edge
{
int pos,c;
int next;
}E[maxm];
int head[maxn];
int dis[maxn],gap[maxn],cur[maxn],pre[maxn];
int map[maxn][maxn];
bool p[maxn][maxn];
int T,n,m,sum;
int s,t,nodenum,NE;
void init()
{
freopen("hoj2713.in","r",stdin);
freopen("hoj2713.out","w",stdout);
}
void insert(int u,int v,int c)
{
E[NE].c = c;E[NE].pos = v;
E[NE].next = head[u];head[u] = NE++;
E[NE].c = 0;E[NE].pos = u;
E[NE].next = head[v];head[v] = NE++;
}
void checkmin(int &a,int b)
{
if(a == -1 || a > b)a = b;
}
void build_map()
{
s = 0,t = n * m + 1;
nodenum = t + 1;
bool flag = true;
for(int i = 1;i <= m;i++)
{
p[1][i] = flag;
flag = !flag;
}
for(int i = 2;i <= n;i++)
for(int j = 1;j <= m;j++)
p[i][j] = !p[i-1][j];
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
if(p[i][j])
{
insert(s,(i - 1) * m + j,map[i][j]);
if(i - 1 >= 1)insert((i - 1) * m + j,(i - 2) * m + j,inf);
if(i + 1 <= n)insert((i - 1) * m + j,i * m + j,inf);
if(j - 1 >= 1)insert((i - 1) * m + j,(i - 1) * m + j - 1,inf);
if(j + 1 <= m)insert((i - 1) * m + j,(i - 1) * m + j + 1,inf);
}
else insert((i - 1) * m + j,t,map[i][j]);
}
}
}
int sap()
{
memset(dis,0,sizeof(dis));
memset(gap,0,sizeof(gap));
for(int i = s;i <= t;i++)cur[i] = head[i];
int u = pre[s] = s,maxflow = 0,aug = -1;
gap[s] = nodenum;
while(dis[s] < nodenum)
{
loop: for(int &i = cur[u];i != -1;i = E[i].next)
{
int v = E[i].pos;
if(E[i].c && dis[u] == dis[v] + 1)
{
checkmin(aug,E[i].c);
pre[v] = u;
u = v;
if(v == t)
{
maxflow += aug;
for(u = pre[u];v != s;v = u,u = pre[u])
{
E[cur[u]].c -= aug;
E[cur[u]^1].c += aug;
}
aug = -1;
}
goto loop;
}
}
int mind = nodenum;
for(int i = head[u];i != -1;i = E[i].next)
{
int v = E[i].pos;
if(E[i].c && (mind > dis[v]))
{
cur[u] = i;
mind = dis[v];
}
}
if((--gap[dis[u]]) == 0)break;
gap[dis[u] = mind + 1]++;
u = pre[u];
}
return maxflow;
}
void solve()
{
memset(E,0,sizeof(E));
memset(head,-1,sizeof(head));
memset(p,false,sizeof(p));
NE = 0;
build_map();
int ans = sum - sap();
printf("%d\n",ans);
}
void readdata()
{
scanf("%d",&T);
while(T--)
{
memset(map,0,sizeof(map));
sum = 0;
scanf("%d%d",&n,&m);
for(int i = 1;i <= n;i++)
{
for(int j = 1;j <= m;j++)
{
scanf("%d",&map[i][j]);
sum += map[i][j];
}
}
solve();
}
}
int main()
{
init();
readdata();
return 0;
}