A - Can you find it?

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

求三個數表中是否有滿足和爲X的三個數,先求前兩個數表的和並排序,再枚舉第三個數表的數字,用二分搜索法查找和數組裏面是否有滿足條件的數字,不需要查重。

#include <iostream>
#include <algorithm>
using namespace std;
#define MAXN 505

int a[MAXN];
int b[MAXN];
int c[MAXN];
int d[MAXN * MAXN];

int bs(int key, int num)
{
    int lo=0,hi=num;
    int mi;
    while(lo<=hi)
    {
        mi=((hi-lo)>>1)+lo;//lo和hi比較大的時候相加可能爆int
        if(d[mi]==key) return mi;
        else if(d[mi]<key) lo=mi+1;
        else hi=mi-1;
    }
    return -1;//未找到
}

int main()
{
    int t = 1;
    int l,n,m;
    int s,key;
    int i,j;
    int isYes = 0;
    while(cin >> l >> n >> m)
    {
        for(i = 0; i < l; i++)
            cin >> a[i];
        for(i = 0; i < n; i++)
            cin >> b[i];
        for(i = 0; i < m; i++)
            cin >> c[i];
        cin >> s;
        for(int i = 0; i < l; i++)
            for(int j = 0; j < n; j++)
                d[i*n+j] = a[i] + b[j];
        sort(d, d+l*n);
        cout << "Case " << t << ":" << endl;
        t++;
        while(s--)
        {
            cin >> key;
            for(i = 0; i < m; i++)
            {
                if(bs(key - c[i], l * n) != -1)
                {
                    isYes = 1;
                    cout << "YES" << endl;
                    break;
                }
            }
            if(isYes != 1)
                cout << "NO" << endl;
            isYes = 0;
        }
    }
    return 0;
}
發佈了33 篇原創文章 · 獲贊 0 · 訪問量 1萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章