#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
using namespace std;
const int maxn = 310;
struct Edge
{
int from,to,cap,flow,cost;
};
struct MCMF
{
int n,m,s,t;
vector<Edge> edges;
vector<int> G[maxn];
int inq[maxn];
int d[maxn];
int p[maxn];
int a[maxn];
void init(int n){
this->n=n;
for (int i=0;i<=n;i++) G[i].clear();
edges.clear();
}
void add(int from,int to,int cap,int cost)
{
edges.push_back((Edge){from,to,cap,0,cost});
edges.push_back((Edge){to,from,0,0,-cost});
m=edges.size();
G[from].push_back(m-2);
G[to].push_back(m-1);
}
} TF;
char mat[15][15];
int N,M,K;
int id[15][15];
int S,T;
bool Bellman(int s,int t,int &flow,int &cost)
{
for (int i=0;i<=2*N*M+2;i++) TF.d[i]=(1<<30);
memset(TF.inq,0,sizeof TF.inq);
TF.d[s]=0;TF.inq[s]=1;TF.a[s]=1<<30;
queue<int> Q;
Q.push(s);
while (!Q.empty())
{
int u=Q.front();Q.pop();
TF.inq[u]=0;
for (int i=0;i<TF.G[u].size();i++){
Edge & e=TF.edges[TF.G[u][i]];
if (e.cap>e.flow && TF.d[e.to]>TF.d[u]+e.cost){
TF.d[e.to]=TF.d[u]+e.cost;
TF.p[e.to]=TF.G[u][i];
TF.a[e.to]=min(TF.a[u],e.cap-e.flow);
if (!TF.inq[e.to]) {Q.push(e.to);TF.inq[e.to]=1;}
}
}
}
if (TF.d[t]>=(1<<30)) return false;
flow+=TF.a[t];
cost+=TF.d[t];
int u=t;
while (u!=s){
TF.edges[TF.p[u]].flow+=TF.a[t];
TF.edges[TF.p[u]^1].flow-=TF.a[t];
u=TF.edges[TF.p[u]].from;
}
return true;
}
int mincost()
{
int flow=0,cost=0;
while (Bellman(S,T,flow,cost));
if (flow==N*M)
return -cost;
else return -1;
}
int main()
{
int t;
scanf("%d",&t);
int kase=0;
while (t--)
{
scanf("%d%d%d",&N,&M,&K);
S=0,T=2*N*M+2;
TF.init(T);
for (int i=1;i<=N;i++) scanf("%s",mat[i]+1);
for (int i=1;i<=N;i++){
for (int c=1;c<=M;c++){
for (int j=i+1;j<=N;j++){
int cost=0;
cost+=j-i-1;
if (mat[i][c]==mat[j][c]) cost-=mat[i][c]-'0';
TF.add((i-1)*M+c,N*M+(j-1)*M+c,1,cost);
}
for (int j=c+1;j<=M;j++){
int cost=0;
cost+=j-c-1;
if (mat[i][c]==mat[i][j]) cost-=mat[i][c]-'0';
TF.add((i-1)*M+c,N*M+(i-1)*M+j,1,cost);
}
}
}
for (int i=1;i<=N;i++){
for (int j=1;j<=M;j++){
TF.add(S,(i-1)*M+j,1,0);
TF.add(N*M+(i-1)*M+j,T,1,0);
}
}
TF.add(S,2*N*M+1,K,0);
for (int i=N*M+1;i<=2*N*M;i++){
TF.add(2*N*M+1,i,1,0);
}
printf("Case %d : %d\n",++kase,mincost());
}
return 0;
}
tjut 4862
最新推荐文章于 2019-01-27 21:10:00 发布