HDU 2141 Can you find it?(暴力+二分)

Can you find it?

Time Limit: 10000/3000 MS (Java/Others)    Memory Limit: 32768/10000 K (Java/Others)
Total Submission(s): 20473    Accepted Submission(s): 5192


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
 
真是醉了,用set本来觉得方法挺好,挺巧,就是爆内存,就因为多开了个数组,malloc都不行。
不用set也可以,开3个数组也不会爆!
大体题意:
输入3组数组,问是否能在3组数组中找出三个数来,使得他们的和是X
思路:
三层循环肯定爆,所以可以枚举前两个数组和的所有情况,输入一个数,枚举C数组,用二分查找那个数组和的数组。

代码如下:

#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
#include<cstdlib>
#include<set>
using namespace std;
const int maxn = 500 + 10;
int L,M,N,cnt=0,cnt2;
int a[maxn],b[maxn*maxn],c[maxn],ok;
bool my_find(int k){
    int l=0,r=cnt2-1;
    while(l <= r){
        int mid = l + (r - l) / 2;
        if (b[mid] == k)return true;
        if (b[mid] < k)l = mid+1;
        else r = mid-1;
    }
    return false;
}
int main()
{
    while(cin >> L >> M >> N){
        cnt2 = 0;
        for (int i = 0; i < L; ++i)scanf("%d",&a[i]);
        for (int i = 0; i < M; ++i){
            int h;
            scanf("%d",&h);
            for (int j = 0; j < L; ++j)b[cnt2++]=a[j]+h;
        }
        for (int i = 0; i < N; ++i)scanf("%d",&c[i]);
        sort(c,c+N);
        sort(b,b+cnt2);
        int cont,sum;
        cin >> cont;
        printf("Case %d:\n",++cnt);
        while(cont--){
            ok=false;
            cin >> sum;
            for (int i = 0; i < N; ++i){
                int k = sum - c[i];
                //if (k < 0)goto TT;
                if (my_find(k)){
                    ok=true;
                    break;
                }
            }
                if (ok)printf("YES\n");
                else printf("NO\n");
        }
    }
    return 0;
}


你可能感兴趣的:(C语言)