C語言排序--Can you find it?(Hdu 2141)
Problem Description Give you three sequences of numbers A, B, C, then we give you a number X. Now you need to calculate if you can find the three numbers Ai, Bj, Ck, which satisfy the formula Ai+Bj+Ck = X.
Input There are many cases. Every data case is described as followed: In the first line there are three integers L, N, M, in the second line there are L integers represent the sequence A, in the third line there are N integers represent the sequences B, in the forth line there are M integers represent the sequence C. In the fifth line there is an integer S represents there are S integers X to be calculated. 1<=L, N, M<=500, 1<=S<=1000. all the integers are 32-integers.
Output For each case, firstly you have to print the case number as the form "Case d:", then for the S queries, you calculate if the formula can be satisfied or not. If satisfied, you print "YES", otherwise print "NO".
Sample Input
3 3 3
1 2 3
1 2 3
1 2 3
3
1
4
10
Sample Output
Case 1:
NO
YES
NO
題目大意: 輸入數據第一排是三個數,分別表示三個數組的大小. (三個數組的大小的最大值都是500) 接下來的三排是輸入三個數組的數字. 然後第四排輸入一個整數n表示接下來n排測試數據. 每個測試數據是一個整數m. 要求在上面的三個數組中每個數組找一個數(共三個數)相加之和等於該測試數據m.如果找到了就輸出YES,如果不存在這樣的三個數那麼就輸出NO.
大致思路:
因為題目給的數據每個數組最多有500個元素,那麼如果三個for循環就是500*500*500肯定超時,(姑且我們這裡把第一第二第三數組叫為a,b,c數組) 這個時候我們可以把c數組排序,然後用兩個for循環枚舉a,b兩個數組中所有組合的和k,然後再用二分查找在c數組中查找m-k這個數.這樣時間最多為500*500*log500≈2250000 或者是在a,b兩個數組中所有組合的和k組成的數組中去二分查找m-c[i]這個數(以下代碼便是).
代碼如下:
#include
#include
using namespace std;
int a[501],b[501],m[250001],c[501],flag;
void find(int a[],int b,int n)
{
int left,right,mid;
left=0,right=n-1;
while(left<=right)
{
mid=(left+right)/2;
if(a[mid]==b)
{
flag=1;
break;
}
else if(a[mid]>b)
right=mid-1;
else
left=mid+1;
}
}
int main()
{
int i,j,k,n1,n2,n3,n4,ci=0;
while(scanf("%d%d%d",&n1,&n2,&n3)!=EOF)
{
ci++;
for(i=0;i