2017年ICPC中国大陆区域赛真题(下)A题

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接: https://blog.csdn.net/qq_43735840/article/details/99704932

题目网址点击进入

problem
One day n girls and n boys come to Xi’an to look for a mate. Each girl has a value a[i], each boy has
a value b[i]. Girl i and boy j will fall in love only if a[i] + b[j] ≥ k.
Please help them make pairs as many as possible .

Input
Several test cases .
First line an integer T (1 ≤ T ≤ 10). Indicates the number of test cases.
Then T test cases follows. Each test case begins with two integer N, K (1 ≤ N ≤ 200000,
0 ≤ K ≤ 109
). The next line has N integers indicate a[1] to a[N] (0 ≤ a[i] ≤ 109
). The next line
has N integers indicate b[1] to b[N] (0 ≤ b[i] ≤ 109
)

Output
For each test case, print the answer in a single line.

Sample Input
1
3 4
1 2 3
1 2 3

Sample Output
3

大致题意
有n对男女,每一个人手里一个数字,问最多有几对男女数字之和大于k

思路
一开始看见男女分配的题目,乍眼一看以为二分图,直接就是匈牙利算法上去,压根没注意20W的数据,交了一发T,对于博主是一个再正常不过的事情,问了问队友有没有快一点的二分图算法,队友看了一下开始嘲笑
寻找是否存在男女加起来大于等于k即可,排序一下,当a9与b5刚刚好匹配的时候,那么小于b5的数字便可以直接跳过,当a8寻找时候,利用加法原理,小的配大的,便直接可以从b5开始寻找,所以首先是对于男女直接排序,一个从尾巴一个从前面开始,复杂度省下很多

代码

#include<stdio.h>
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long int LLD;
LLD n,k,boy[200005],girl[200005];///男女数组
int main()
{
    LLD t;
    scanf("%lld",&t);
    while (t--)
    {
        scanf("%lld %lld",&n,&k);
        for (LLD i=0;i<n;i++)
        {
            scanf("%lld",&boy[i]);
        }
        for (LLD i=0;i<n;i++)
        {
            scanf("%lld",&girl[i]);
        }
        sort(boy,boy+n);///分别排序
        sort(girl,girl+n);
        LLD left=0,right=n-1,ans=0;
        for (LLD i=right;i>=0;i--)///男生从尾巴开始
        {
            while (boy[i]+girl[left]<k)///寻找从头开始女生
            {
                left++;
            }
            //printf("%lld\n",left);
            if (boy[i]+girl[left]>=k&&left<n)///left<n防止越界
            {
                ans++;
            }
            if (left>=n-1)
            {
                printf("%lld\n",ans);///全部搜索完了直接跳出结束
                break;
            }
        }
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_43735840/article/details/99704932