版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sugarbliss/article/details/89460556
题目链接:http://acm.zju.edu.cn/onlinejudge/showProblem.do?problemId=5979
题意:给你n个绅士的身高,和m个女士的身高,接下来两行分别是表明对应的的绅士 / 女士想找一个比自己高或矮的异性,0表示希望异性比自己矮,1表示希望异性比自己高。问最大的配对数。
思路:看上去像是一个二分图匹配,实际是个贪心,绅士的0一定是和女士的1配对,我们对绅士和女士的爱好有矮到高排序,并且记录0的个数。然后按01配对贪心即可,时间复杂度。
#include <bits/stdc++.h>
using namespace std;
const int N = 2e5 + 7;
struct node
{
int height, like;
}man[N], lady[N];
int n, m;
bool cmp(node a, node b)
{
if(a.like == b.like)
return a.height < b.height;
return a.like < b.like;
}
int main()
{
int t; scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i = 0; i < n; i++)
scanf("%d",&man[i].height);
for(int i = 0; i < m; i++)
scanf("%d",&lady[i].height);
int mcnt = 0, lcnt = 0;
for(int i = 0; i < n; i++)
{
scanf("%d",&man[i].like);
if(!man[i].like) mcnt++;
}
for(int i = 0; i < m; i++)
{
scanf("%d",&lady[i].like);
if(!lady[i].like) lcnt++;
}
sort(man, man + n, cmp); sort(lady, lady + m, cmp);
int j = lcnt, ans = 0;
for(int i = 0; i < mcnt && j < m; i++)
{
if(lady[j].height < man[i].height)
ans++, j++;
}
j = mcnt;
for(int i = 0; i < lcnt && j < n; i++)
{
if(lady[i].height > man[j].height)
ans++, j++;
}
printf("%d\n",ans);
}
}