题目链接
题目详情
You are given two arrays A and B consisting of integers, sorted in non-decreasing order. Check whether it is possible to choose k numbers in array A and choose m numbers in array B so that any number chosen in the first array is strictly less than any number chosen in the second array.
Input
The first line contains two integers nA, nB (1 ≤ nA, nB ≤ 105), separated by a space — the sizes of arrays A and B, correspondingly.
The second line contains two integers k and m (1 ≤ k ≤ nA, 1 ≤ m ≤ nB), separated by a space.
The third line contains nA numbers a1, a2, ... anA ( - 109 ≤ a1 ≤ a2 ≤ ... ≤ anA ≤ 109), separated by spaces — elements of array A.
The fourth line contains nB integers b1, b2, ... bnB ( - 109 ≤ b1 ≤ b2 ≤ ... ≤ bnB ≤ 109), separated by spaces — elements of array B.
Output
Print "YES" (without the quotes), if you can choose k numbers in array A and m numbers in array B so that any number chosen in array A was strictly less than any number chosen in array B. Otherwise, print "NO" (without the quotes).
input
3 3
2 1
1 2 3
3 4 5
output
YES
input
3 3
3 3
1 2 3
3 4 5
output
NO
input
5 2
3 1
1 1 1 1 1
2 2
output
YES
题目大意及解题思路
大意:
两个由整数组成的数组A和B,它们按非递减顺序排序。检查是否可以在数组A中选择k个数字,在数组B中选择m个数字,以便在第一个数组中选择的任何数字都严格小于在第二个数组中选定的任何数字。Input第一行包含两个整数nA, nB,由一个空格分隔-相应地是数组a和B的大小。第二行包含两个整数k和m。第三行包含nA个数字a1, a2, ... 由空格分隔。第四行包含nB个整数b1, b2中, 用空格分隔-数组B的元素。如果可以在数组A中选择k个数字,在数组B中选择m个数字,使数组A中所选的任何数字严格小于数组B中所选任何数字,则输出打印“YES”(不带引号)。否则,打印“NO”。
解题思路:
这道题我们可以用贪心思想解决,首先将A从小到大排序,B从大到小排,再判断A的前k个是否都小于B的前m个。但是这样做会超时的(注释掉的代码!!!)其实我们只需要排完序后,看A的第k个是不是小于等于b的第m个即可。但最后发现他给的数组竟然是有序的,那么直接判断A的第k个是不是小于等于b的第nb-m+1个即可。
AC代码
#include<iostream>
#include<algorithm>
using namespace std;
typedef long long ll;
int main()
{
int na, nb, k, m, a[100010],b[100010];
cin >> na >> nb >> k >> m;
for (int i = 0; i < na; i++) cin >> a[i];
for (int i = 0; i < nb; i++) cin >> b[i];
/*sort(a, a + na);
sort(b, b + nb, cmp);
bool flage = false;
for (int i = 0; i < k; i++)
{
for (int j = 0; j < m; j++)
{
if (a[i] >= b[j])
{
flage = true;
break;
}
}
}
if (flage) cout << "NO";
else cout << "YES";*/
if (a[k-1] < b[nb-m])printf("YES\n");
else printf("NO\n");
return 0;
}