题意:给定一个nn的矩阵,“.”表示水,“#”表示油,现在要用一个12的勺子取油,问最多能取多少次。
思路:把所有油当作左右两个节点,相邻的话就连一条边,然后求最大匹配。
如何证明最后的结果一定是对称的:对于一个对称的匹配方案,如果左边的部分存在增广路,右边的部分一定也存在增广路,所以结果一定对称。
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <algorithm>
//#include <map1>
#include <queue>
#include <vector>
#include <stack>
#include <string>
#define N 650
#define ll long long
#define INF 0x7fffffff
using namespace std;
int dx[4] = {-1,1,0,0};
int dy[4] = {0,0,-1,1};
char map[N][N];
int num[N][N];
vector<int>con[N*N];
bool used[N*N];
int match[N*N];
int cases;
int n,cnt;
bool found(int x){
int len = con[x].size();
for(int i=0;i<len;i++){
int y = con[x][i];
if(!used[y]){
used[y] = 1;
if(!match[y] || found(match[y])){
match[y] = x;
return 1;
}
}
}
return 0;
}
int main(){
int i,j;
int x,y;
scanf("%d",&cases);
int t = 0;
while (cases > 0)
{
cases--;t++;
memset(map,0,sizeof(map));
memset(num,0,sizeof(num));
memset(match,0,sizeof(match));
for(i=1;i<N*N;i++){
con[i].clear();
}
cnt = 0;
scanf("%d",&n);
for(i=1;i<=n;i++){
getchar();
for(j=1;j<=n;j++){
scanf("%c",&map[i][j]);
if(map[i][j] == '#'){
cnt++;
num[i][j] = cnt;
}
}
}
for(i=1;i<=n;i++){
for(j=1;j<=n;j++){
if(num[i][j]){
for(int k=0;k<4;k++){
if(num[i+dx[k]][j+dy[k]]){
con[num[i][j]].push_back(num[i+dx[k]][j+dy[k]]);
}
}
}
}
}
int ans = 0;
for(i=1;i<=cnt;i++){
memset(used,0,sizeof(used));
if(found(i)){
ans++;
}
}
printf("Case %d: %d\n",t,ans/2);
}
return 0;
}