HDU 4185 Oil Skimming 匈牙利

用1*2的木板覆盖矩阵中的‘#’,(木板要覆盖的只能是‘#’),问最多能用几个木板覆盖


很典型的二分匹配问题,将矩阵中的点分成俩种,下标i+j为奇数和偶数俩种,即把矩阵当成一个黑白棋盘,然后用匈牙利二分匹配


#include 
#include 
#include 
#include 
#include 
#define rep(i, j, k) for(int i = j; i <= k; i++)
using namespace std;
int n, cnt, a[609][609];
int link[1009], done[1009], ans;
int edge[1009][1009];
bool dfs (int x)
{
    rep (i, 1, cnt)
        if (edge[x][i] != 0 && done[i] == 0)
        {
            int to = i;
            done[to] = 1;
            if (link[to] == -1 || dfs (link[to]))
            {
                link[to] = x;
                return 1;
            }
        }
    return 0;
}
void init ()
{
    ans = cnt = 0;
    memset (link, -1, sizeof (link));
    memset (edge, 0, sizeof (edge));
}
int main ()
{
    int ti;
    cin >> ti;
    rep (ff, 1, ti)
    {
        init ();
        cin >> n;
        rep (i, 1, n)
        {
            char s[609];
            scanf ("%s", s);
            rep (j, 1, n)
                if (s[j - 1] == '#')
                    a[i][j] = ++cnt;
                else
                    a[i][j] = 0;
        }
        rep (i, 1, n)
            rep (j, 1, n)
                if (a[i][j])
                {
                    if (i > 1 && a[i - 1][j])
                        edge[ a[i][j] ][ a[i - 1][j] ] = 1;
                    if (i < n && a[i + 1][j])
                        edge[ a[i][j] ][ a[i + 1][j] ] = 1;
                    if (j > 1 && a[i][j - 1])
                        edge[ a[i][j] ][ a[i][j - 1] ] = 1;
                    if (j < n && a[i][j + 1])
                        edge[ a[i][j] ][ a[i][j + 1] ] = 1;
                }
        rep (i, 1, cnt)
        {
            memset (done, 0, sizeof (done));
            if (dfs (i))
                ans++;
        }
        printf ("Case %d: ", ff);
        cout << ans / 2 << endl;
    }
    return 0;
}


你可能感兴趣的:(hdu,二分图)