[ZJOI 2007] 矩阵游戏

[题目链接]

          https://www.lydsy.com/JudgeOnline/problem.php?id=1059

[算法]

         二分图最大匹配

         时间复杂度 : O(N^3)

[代码]

        

#include<bits/stdc++.h>
using namespace std;
#define MAXN 210

struct edge
{
        int to , nxt;
} e[MAXN * MAXN];

int n , tot;
int match[MAXN],head[MAXN];
bool visited[MAXN];

template <typename T> inline void chkmax(T &x,T y) { x = max(x,y); }
template <typename T> inline void chkmin(T &x,T y) { x = min(x,y); }
template <typename T> inline void read(T &x)
{
    T f = 1; x = 0;
    char c = getchar();
    for (; !isdigit(c); c = getchar()) if (c == '-') f = -f;
    for (; isdigit(c); c = getchar()) x = (x << 3) + (x << 1) + c - '0';
    x *= f;
}
inline void addedge(int u,int v)
{
        tot++;
        e[tot] = (edge){v,head[u]};
        head[u] = tot;
}
inline bool hungary(int u)
{
        for (int i = head[u]; i; i = e[i].nxt)
        {
                int v = e[i].to;
                if (!visited[v])
                {
                        visited[v] = true;
                        if (!match[v] || hungary(match[v]))
                        {
                                match[v] = u;
                                return true;        
                        }        
                }        
        }        
        return false;
}

int main()
{
        
        int T;
        read(T);
        while (T--)
        {
                read(n);
                tot = 0;
                for (int i = 1; i <= n; i++) head[i] = 0;
                for (int i = 1; i <= n; i++)
                {
                        for (int j = 1; j <= n; j++)
                        {
                                int x;
                                read(x);
                                if (x == 1) addedge(i,j);
                        }
                }
                memset(match,0,sizeof(match));
                int t = 0;
                for (int i = 1; i <= n; i++)    
                {
                        memset(visited,false,sizeof(visited));
                        if (hungary(i))
                                t++;        
                }    
                if (t == n) printf("Yes\n");
                else printf("No\n");
        }
        
        return 0;
    
}

 

posted @ 2018-10-01 11:47  evenbao  阅读(119)  评论(0编辑  收藏  举报