HDU4185 Oil Skimming(二分圖匹配,匈牙利演算法)
Problem Description
Thanks to a certain “green” resources company, there is a new
profitable industry of oil skimming. There are large slicks of crude
oil floating in the Gulf of Mexico just waiting to be scooped up by
enterprising oil barons. One such oil baron has a special plane that
can skim the surface of the water collecting oil on the water’s
surface. However, each scoop covers a 10m by 20m rectangle (going
either east/west or north/south). It also requires that the rectangle
be completely covered in oil, otherwise the product is contaminated by
pure ocean water and thus unprofitable! Given a map of an oil slick,
the oil baron would like you to compute the maximum number of scoops
that may be extracted. The map is an NxN grid where each cell
represents a 10m square of water, and each cell is marked as either
being covered in oil or pure water.
Input
The input starts with an integer K (1 <= K <= 100) indicating the
number of cases. Each case starts with an integer N (1 <= N <= 600)
indicating the size of the square grid. Each of the following N lines
contains N characters that represent the cells of a row in the grid. A
character of ‘#’ represents an oily cell, and a character of ‘.’
represents a pure water cell.
Output
For each case, one line should be produced, formatted exactly as
follows: “Case X: M” where X is the case number (starting from 1) and
M is the maximum number of scoops of oil that may be extracted.
Sample Input
1
6
......
.##...
.##...
....#.
....##
......
Sample Output
Case 1: 3
思路
有一個石油大亨要在一片#
代表這個地方是石油,.
代表這個地方是海水,問在這一片水域,最多能打撈多少石油(不能石油和海水一起撈)。
先給石油編上號碼,編號為:1 2 3 4 5…這種,然後我們遍歷這個區域,如果在
因為建立的是雙向邊,所以要最後結果除以2
程式碼
#include <bits/stdc++.h>
using namespace std;
#define mem(a,b) memset(a,b,sizeof(a))
const int N=1000+20;
int e[N][N],vis[N],match[N],n,temp[N][N],num;
char s[N][N];
int dfs(int u)
{
for(int i=1; i<=num; i++)
{
if(e[u][i]&&!vis[i])
{
vis[i]=1;
if(!match[i]||dfs(match[i]))
{
match[i]=u;
return 1;
}
}
}
return 0;
}
int query()
{
mem(match,0);
int sum=0;
for(int i=1; i<=num; i++)
{
mem(vis,0);
if(dfs(i))sum++;
}
return sum;
}
int main()
{
int t,q=1;
scanf("%d",&t);
while(t--)
{
mem(temp,0);
mem(e,0);
num=0;
scanf("%d",&n);
for(int i=1; i<=n; i++)
{
scanf("%s",s[i]+1);
for(int j=1; j<=n; j++)
if(s[i][j]=='#')
temp[i][j]=++num;
}
for(int i=1; i<=n; i++)
for(int j=1; j<=n; j++)
if(s[i][j]=='#')
{
if(i!=1&&s[i-1][j]=='#') e[temp[i][j]][temp[i-1][j]]=1;
if(j!=1&&s[i][j-1]=='#') e[temp[i][j]][temp[i][j-1]]=1;
if(i!=n&&s[i+1][j]=='#') e[temp[i][j]][temp[i+1][j]]=1;
if(j!=n&&s[i][j+1]=='#') e[temp[i][j]][temp[i][j+1]]=1;
}
printf("Case %d: %d\n",q++,query()/2);
}
return 0;
}