HDU 2819 Swap 最大匹配问题

交换图的某些行或者是某些列(可以都换),使得这个N*N的图对角线上全部都是1.


建立二分图,左边表示的是横坐标,右边表示纵坐标,所以范围都是1~N,然后如果a[i][j]是1,那我们就从X的i向Y的j引一条边,然后直接求最大匹配数即可


#include 
#include 
#include 
#include 
#define rep(i, j, k) for(int i = j; i <= k; i++)

using namespace std;

int n, a[109][109], edge[109][109], link[109], done[109], ans, ret, x0, y0;
int ans1[10009], ans2[10009];

bool dfs (int x)
{
    rep (i, 1, n)
        if (edge[x][i] && !done[i])
        {
            done[i] = 1;
            if (link[i] == -1 || dfs (link[i]))
            {
                link[i] = x;
                return 1;
            }
        }
    return 0;
}

//13:32
int main ()
{
    while (scanf ("%d", &n) == 1)
    {
        memset (edge, 0, sizeof (edge));
        memset (a, 0, sizeof (a));
        rep (i, 1, n)
            rep (j, 1, n)
                scanf ("%d", &a[i][j]);
        rep (i, 1, n)
            rep (j, 1, n)
                if (a[i][j])
                    edge[i][j] = 1;
        memset (link, -1, sizeof (link));
        ans = 0;
        rep (i, 1, n)
        {
            memset (done, 0, sizeof (done));
            if (dfs (i))
                ans++;
        }
        if (ans != n)
            printf ("-1\n");
        else
        {
            ret = 0;
            /*ret = 0;
            rep (i, 1, n)
                if (link[i] != i)
                {
                    ans1[++ret] = link[i];
                    ans2[ret] = link[link[i]];
                    swap (link[i], link[ link[i] ]);
                }*/
            rep (i, 1, n)
            {
                int now;
                for (now = 1; now <= n; now++)
                    if (link[now] == i)
                        break;
                if (now != i)
                {
                    ans1[++ret] = i;
                    ans2[ret] = now;
                    swap (link[i], link[now]);
                }
            }
            cout << ret << endl;
            rep (i, 1, ret)
                printf ("C %d %d\n", ans1[i], ans2[i]);
        }
    }
    return 0;
}


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