Description
One day nn girls and nn boys come to Xi’an to look for a mate . Each girl has a value a[i]a[i] , each boy has a value b[i]b[i] . Girl ii and boy jj will fall in love only if a[i]+b[j] \ge ka[i]+b[j]≥k .
Please help them make pairs as many as possible .
Input
Several test cases .
First line an integer TT (1 \le T \le 10)(1≤T≤10) . Indicates the number of test cases.
Then TT test cases follows . Each test case begins with two integer NN, KK (1 \le N \le 200000 , 0 \le K \le 10^9)(1≤N≤200000,0≤K≤10
9
) . The next line has NN integers indicate a[1]a[1] to a[N]a[N] (0 \le a[i] \le 10^9)(0≤a[i]≤10
9
) . The next line has NN integers indicate b[1]b[1] to b[N]b[N] (0 \le b[i] \le 10^9)(0≤b[i]≤10
9
)
Output
For each test case , print the answer in a single line.
样例输入
1
3 4
1 2 3
1 2 3
样例输出
3
题目大意
一群男生一群女生,双方人数相同,每个人都有自己的一个数值,现给定一个指标值k,只有一个男生和一个女生的数值和大于k时才能成为lover,求最多能组成多少对lover?
思路
为了保证组成最多的lover,那么需要让一个尽可能大地值与一个尽可能小地值匹配,这样才可以保证组成对数最多。
那么只需要对两组数值进行排序,让一组的大值与另一组小值不断匹配即可。
#include <stdio.h>
#include <stdlib.h>
int cmp(int *a,int *b)
{
return *a-*b;
}
int main()
{
int t;
scanf("%d",&t);
while(t--)
{
int n,k;
int a[200001],b[200001];
int hg=0,hb=0;
int ans=0;
int i,j;
scanf("%d%d",&n,&k);
for(i=0;i<n;i++)
scanf("%d",&a[i]);
for(i=0;i<n;i++)
scanf("%d",&b[i]);
qsort(a,n,sizeof(a[0]),cmp);
qsort(b,n,sizeof(b[0]),cmp);
if(a[n-1]+b[n-1]<k)//特判:当两组最大值都无法满足条件的话即可输出0
{
printf("0\n");
continue;
}
for(i=n-1,j=0;i>=0;i--){//一个从大值开始,另一个从小值开始
for(;j<n;j++){
if(a[j]+b[i]>=k){
ans++;
j=j+1;//当一个小值与尽可能大的值都无法匹配的话那么这个值就可以舍去了
break;
}
}
}
printf("%d\n",ans);
}
}