二分图经典模型(洛谷 P1263 宫廷守卫)

题目链接
乍一看,经典搜索or状压dp啊。但是200的数据量打消了我这个念头。标签里有图论,就往图论上想。发现应该是个二分图,而且是一个经典的模型,曾在蓝皮书上看见过类似的。
我们先得出无墙壁连续行块,连续列块。并给之编号。
例如样例(每个位置所属的连续行块及连续列块):
列:

0 1 2 3
0 0 0 3
4 5 6 0

行:

0 8 8 8
0 0 0 9
7 7 7 0

我们针对每个空位置,将他所属行块、列块连边,求跑一边最大匹配就行了。
下面是ac代码:

#include 
#include 
#include 
#include 
#include 
#include 
#include 
#include 
#define ll long long
using namespace std;
const int N = 2e5+5;
int tot;
int he[N], ne[N], ver[N];
int match[N];
bool vis[N];
int ans;
void init()
{
    memset(match, 0, sizeof(match));
}
void add(int x, int y)
{
    ver[++tot] = y;
    ne[tot] = he[x];
    he[x] = tot;
}
int mx;
bool dfs(int x)
{
    for (int i = he[x]; i; i = ne[i])
    {
        int y = ver[i];
        if (!vis[y])
        {
            vis[y] = 1;
            if (!match[y] || dfs(match[y]))
            {
                match[y] = x;
                return 1;
            }
        }
    }
    return 0;
}
int m, n;
void getans()
{
   for (int i = 1; i <= mx; i++)
    {
        memset(vis, 0, sizeof(vis));
        if (dfs(i)) ans++;
    }
}
int mp[256][256];
int idn[256][256];
int idm[256][256];
int gg[N];
int cnt = 0;
int main()
{
    scanf("%d%d", &n, &m);
    for (int i = 1; i <= m; i++) mp[0][i] = 2;
    for (int i = 1; i <= n; i++) mp[i][0] = 2;
    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            scanf("%d", &mp[i][j]);
    for (int i = 1; i <= n; i++)
    {
        for (int j = 1; j <= m; j++)
        {
            if (mp[i][j] == 2) continue;
            if (mp[i-1][j] == 2) idn[i][j] = ++cnt, gg[cnt] = j;
            else idn[i][j] = idn[i-1][j];
        }
    }
    mx = cnt;
    for (int i = 1; i <= m; i++)
    {
        for (int j = 1; j <= n; j++)
        {
            if (mp[j][i] == 2) continue;
            if (mp[j][i-1] == 2) idm[j][i] = ++cnt, gg[cnt] = j;
            else idm[j][i] = idm[j][i-1];
        }
    }

    for (int i = 1; i <= n; i++)
        for (int j = 1; j <= m; j++)
            if (!mp[i][j])
            {add(idn[i][j], idm[i][j]);}
    getans();
    printf("%d\n", ans);
    for (int i = mx+1; i <= cnt; i++)
        if (match[i])
            printf("%d %d\n", gg[i], gg[match[i]]);

}

你可能感兴趣的:(憨批的图论,二分图)