【二分匹配】 HDOJ 5093 Battle ships

二分匹配,行列匹配就行了。。。

#include <iostream>
#include <queue> 
#include <stack> 
#include <map> 
#include <set> 
#include <bitset> 
#include <cstdio> 
#include <algorithm> 
#include <cstring> 
#include <climits>
#include <cstdlib>
#include <cmath>
#include <time.h>
#define maxn 20005
#define maxm 4000005
#define eps 1e-10
#define mod 1000000007
#define INF 1e9
#define lowbit(x) (x&(-x))
#define mp make_pair
#define ls o<<1
#define rs o<<1 | 1
#define lson o<<1, L, mid 
#define rson o<<1 | 1, mid+1, R 
typedef long long LL;
typedef unsigned long long ULL;
//typedef int LL;
using namespace std;

struct Edge
{
    int v;
    Edge *next;
}pool[maxm], *H[maxn], *edges;
char g[100][100];
int gg[100][100];
int vis[maxn];
int res[maxn];
int n, m;

void addedges(int u, int v)
{
    edges->v = v;
    edges->next = H[u];
    H[u] = edges++;
}

void init(void)
{
    edges = pool;
    memset(g, 0, sizeof g);
    memset(gg, 0, sizeof gg);
    memset(H, 0, sizeof H);
    memset(res, -1, sizeof res);
}

void read(void)
{
    scanf("%d%d", &n, &m);
    for(int i = 1; i <= n; i++)
        scanf("%s", g[i] + 1);
}

bool find(int u)
{
    for(Edge *e = H[u]; e; e = e->next) {
        if(!vis[e->v]) {
            vis[e->v] = 1;
            if(res[e->v] == -1 || find(res[e->v])) {
                res[e->v] = u;
                return true;
            }
        }
    }
    return false;
}

void debug(int tt)
{
    for(int i = 1; i <= tt; i++) {
        printf("%d ::: ", i);
        for(Edge *e = H[i]; e; e = e->next)
            printf("%d ", e->v);
        printf("\n");
    }
}

void work(void)
{
    int t1 = 0, t2 = 0, ok;
    for(int i = 1; i <= m; i++) {
        ok = 1;
        for(int j = 1; j <= n; j++) {
            if(g[j][i] == '*') {
                if(ok) ++t2;
                gg[j][i] = t2;
                ok = 0;
            }
            if(g[j][i] == '#') ok = 1;
        }
    }
    t1 = t2;
    //printf("AAAAAAAAAAa %d\n", t2);
    for(int i = 1; i <= n; i++) {
         ok = 1;
        for(int j = 1; j <= m; j++) {
            if(g[i][j] == '*') {
                if(ok) ++t1;
                addedges(t1, gg[i][j]);
                addedges(gg[i][j], t1);
                ok = 0;
            }
            if(g[i][j] == '#') ok = 1;
        }
    }
    //printf("BBBBBBBBBb %d\n", t1);
    //debug(t2);
    int ans = 0;
    for(int i = 1; i <= t2; i++) {
        memset(vis, 0, sizeof vis);
        if(find(i)) ans++;
        //for(int j = 1; j <= t1; j++) printf("%d %d HHH\n", j, res[j]);
    }
    printf("%d\n", ans);
}

int main(void)
{
    int _;
    while(scanf("%d", &_)!=EOF) {
        while(_--) {
            init();
            read();
            work();
        }
    }

    return 0;
}


你可能感兴趣的:(HDU)