HDU - 1281 二分图匹配
这道题用到二分图匹配。
思路的话,因为一个车占一个x和一个y,要它们不能互相攻击,必定一个x只能匹配至多一个y。(同理y也是这样)。
所以我们可以对 x 和 y 进行二分图匹配。
求出最大匹配数目后,一次删一条边,算这种情况下的最大匹配数目有没有发生改变,如果发生了改变,那么必定是重要点,如果没有发生改变那就不是重要点。然后把这条删掉的边再添加回去,一直重复操作直到结束就好了。
个人觉得这道题用邻接矩阵做更顺手。
代码
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <algorithm>
using namespace std;
typedef long long ll;
const int maxn = 105;
int n, m, k;
bool G[maxn][maxn];
int match[maxn];
bool used[maxn];
bool dfs(int u){
for(int i = 1; i <= m; ++i)
{
if(G[u][i] && !used[i])
{
used[i] = true;
int w = match[i];
if(w < 0 || dfs(w))
{
match[i] = u;
return true;
}
}
}
return false;
}
int Hungary(){
int ans = 0;
memset(match, -1, sizeof(match));
for(int i = 1; i <= n; ++i)
{
memset(used, false, sizeof(used));
if(dfs(i))
ans++;
}
return ans;
}
int main(){
int board = 1;
while(scanf("%d %d %d", &n, &m, &k) != EOF)
{
for(int i = 1; i <= n; i++)
for(int j = 1; j <= m; j++)
G[i][j] = false;
int x, y;
for(int i = 1; i <= k; ++i)
{
scanf("%d %d", &x, &y);
G[x][y] = true;
}
int cnt = Hungary();
int ans = 0;
for(int i = 1; i <= n; ++i)
{
for(int j = 1; j <= m; ++j)
{
if(G[i][j])
{
G[i][j] = false;
if(Hungary() != cnt)
{
ans++;
}
G[i][j] = true;
}
}
}
printf("Board %d have %d important blanks for %d chessmen.\n", board++, ans, cnt);
}
return 0;
}