题目要求
给定N个人,求不能成为夫妇的最大对数
一、准备工作
Their height differs by more than 40 cm.
They are of the same sex.
Their preferred music style is different.
Their favourite sport is the same (they are likely to be fans of different teams and that would result in fighting).
对于这4个条件,挨个建边过于麻烦,我们考虑反着来,满足以上任意一个条件,就是不能成为夫妇的,根据这个发现,我们可以把能成为夫妇的两个点建双向边,然后发现这是个二分图,直接跑匈牙利算法求最大匹配数即可
二、解题过程
1.数据结构
根据题目的输入格式,我们考虑封装结构体
struct note
{
int height;
char sex;
char music[105],sport[105];
}nl[N];
2.建图
数据输入完毕后,我们需要根据条件建图,满足上面任意一条条件就跳过,对于能成为夫妇的两个点加无向边
for (int i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (abs(nl[i].height - nl[j].height) > 40) continue;
if (nl[i].sex == nl[j].sex) continue;
if (strcmp(nl[i].music,nl[j].music) != 0) continue;
if (strcmp(nl[i].sport,nl[j].sport) == 0) continue;
e[i].push_back(j); e[j].push_back(i);
}
}
3.计算答案
跑匈牙利算法求最大匹配数,本题求最大独立集,根据最大独立集 = 二分图顶点数 - 最大匹配数.
mst(match);
int cnt = 0;
for (int i = 1; i <= n; i++)
{
mst(vis);
if (dfs(i)) cnt++;
}
cout << n - cnt / 2 << "\n";
cnt为什么要除以2呢?建的是无向边,所以答案会被累加两次。
AC代码
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
using namespace std;
#define mst(x) memset(x,0,sizeof(x))
#define IOS ios::sync_with_stdio(false),cin.tie(0),cout.tie(0)
const int N = 505;
struct note
{
int height;
char sex;
char music[105],sport[105];
}nl[N];
vector<int> e[N];
int match[N],t,n;
bool vis[N];
bool dfs(int u);
int main()
{
IOS;
cin >> t;
while (t--)
{
cin >> n;
for (int i = 1; i <= n; i++)
{
cin >> nl[i].height >> nl[i].sex >> nl[i].music >> nl[i].sport;
e[i].clear();
}
for (int i = 1; i <= n; i++)
{
for (int j = i + 1; j <= n; j++)
{
if (abs(nl[i].height - nl[j].height) > 40) continue;
if (nl[i].sex == nl[j].sex) continue;
if (strcmp(nl[i].music,nl[j].music) != 0) continue;
if (strcmp(nl[i].sport,nl[j].sport) == 0) continue;
e[i].push_back(j); e[j].push_back(i);
}
}
mst(match);
int cnt = 0;
for (int i = 1; i <= n; i++)
{
mst(vis);
if (dfs(i)) cnt++;
}
cout << n - cnt / 2 << "\n";
}
return 0;
}
bool dfs(int u)
{
for (int i = 0; i < e[u].size(); i++)
{
int v = e[u][i];
if (vis[v]) continue;
vis[v] = true;
if (!match[v] || dfs(match[v]))
{
match[v] = u;
return true;
}
}
return false;
}
562

被折叠的 条评论
为什么被折叠?



