洛谷1894 [USACO4.2]完美的牛栏The Perfect Stall

原题链接

二分图最大匹配板子。
每个奶牛向它愿意去的牛棚连边,跑二分图最大匹配即可。
这里我用的是匈牙利算法。

#include<cstdio>
#include<cstring>
using namespace std;
const int N = 410;
const int M = N * N;
int fi[N], ne[M], di[M], mtc[N], l;
bool v[N];
inline int re()
{
    int x = 0;
    char c = getchar();
    bool p = 0;
    for (; c < '0' || c > '9'; c = getchar())
        p |= c == '-';
    for (; c >= '0' && c <= '9'; c = getchar())
        x = x * 10 + c - '0';
    return p ? -x : x;
}
inline void add(int x, int y)
{
    di[++l] = y;
    ne[l] = fi[x];
    fi[x] = l;
}
bool dfs(int x)
{
    int i, y;
    for (i = fi[x]; i; i = ne[i])
        if (!v[y = di[i]])
        {
            v[y] = 1;
            if (!mtc[y] || dfs(mtc[y]))
            {
                mtc[y] = x;
                return true;
            }
        }
    return false;
}
int main()
{
    int i, j, n, m, x, s = 0;
    n = re();
    re();
    for (i = 1; i <= n; i++)
    {
        m = re();
        for (j = 1; j <= m; j++)
        {
            x = re();
            add(i, x + n);
        }
    }
    for (i = 1; i <= n; i++)
    {
        memset(v, 0, sizeof(v));
        if (dfs(i))
            s++;
    }
    printf("%d", s);
    return 0;
}

猜你喜欢

转载自www.cnblogs.com/Iowa-Battleship/p/9803444.html
今日推荐