思路:
配对的2个点总是一奇一偶,用奇偶点来建二分图,v1是所有奇数点的个数,v2是所有偶数点的个数,假设最大完全匹配了n对,则还剩下没有匹配的v1-n和v2-n个点,这些没有配对的点必须加天线。
所以总数=n+(v1-n)+(v2-n)。
一次RE:是因为用char来建了map,char map[45][15],读入int型会越界。
源代码:
#include <iostream>
#include <fstream>
using namespace std;
int h, w;
int map[45][15];
int result;
int v1, v2;
bool bigraph[410][410];
bool visit[410];
int link[410];
int alone;
bool dfs(int x)
{
for (int y = 1; y <= v2; y++)
{
if (bigraph[x][y] && !visit[y])
{
visit[y] = true;
if (link[y] == 0 || dfs(link[y]))
{
link[y] = x;
return true;
}
}
}
return false;
}
void search()
{
result = 0;
memset(link,0,sizeof(link));
for (int x = 1; x <= v1; x++)
{
memset(visit,false,sizeof(visit));
if (dfs(x))
{
result++;
}
}
}
int main()
{
ifstream in("input.txt");
int cases;
char temp;
in >> cases;
while (cases--)
{
in >> h >> w;
memset(map,0,sizeof(map));
v1 = v2 = 0;
for (int i = 1; i <= h; i++)
{
for (int j = 1; j <= w; j++)
{
in >> temp;
if (temp == '*')
{
if ((i + j) % 2!=0) //奇数点
{
map[i][j] = ++v1;
}
else //偶数点
{
map[i][j] = ++v2;
}
}
}
}
memset(bigraph, false, sizeof(bigraph));
//Construct the bipartite graph
for (int i = 1; i <= h; i++)
{
for (int j = 1; j <= w; j++)
{
if (map[i][j] != 0 && (i + j) % 2 != 0)
{
if (map[i - 1][j] != 0)
{
bigraph[map[i][j]][map[i - 1][j]] = true;
}
if (map[i + 1][j] != 0)
{
bigraph[map[i][j]][map[i + 1][j]] = true;
}
if (map[i][j-1] != 0)
{
bigraph[map[i][j]][map[i][j - 1]] = true;
}
if (map[i][j+1] != 0)
{
bigraph[map[i][j]][map[i][j + 1]] = true;
}
}
}
}
//Hungary Algorithm
search();
//Result
result = (v1 - result) + (v2 - result) + result;
cout << result << endl;
}
system("pause");
return 0;
}