分治(1)

Trouble

Hassan is in trouble. His mathematics teacher has given him a very difficult problem called 5-sum. Please help him.
The 5-sum problem is defined as follows: Given 5 sets S_1,...,S_5 of n integer numbers each, is there a_1 in S_1,...,a_5 in S_5 such that a_1+...+a_5=0?
 

Input

First line of input contains a single integer N (1≤N≤50). N test-cases follow. First line of each test-case contains a single integer n (1<=n<=200). 5 lines follow each containing n integer numbers in range [-10^15, 1 0^15]. I-th line denotes set S_i for 1<=i<=5.
 

Output

For each test-case output "Yes" (without quotes) if there are a_1 in S_1,...,a_5 in S_5 such that a_1+...+a_5=0, otherwise output "No".
 

Sample Input

2
2
1 -1
1 -1
1 -1
1 -1
1 -1
3
1 2 3
-1 -2 -3
4 5 6
-1 3 2
-4 -10 -1

Sample Output

No
Yes

Source

2012 Multi-University Training Contest 4
#include<cstdio>
#include<algorithm>
#define ll __int64
using namespace std;
ll a[5][205];
ll num[2][40005];
int main(){
    int T;
    scanf("%d",&T);
    while(T--){
        int n;
        scanf("%d",&n);
        for(int i = 0; i < 5; i++)
            for(int j = 0; j < n; j++)
                scanf("%I64d",&a[i][j]);
        int cnt = 0;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                num[0][cnt++] = a[0][j] + a[1][i];//2合1;
        sort(num[0],num[0]+cnt);
        int cnt1 = cnt;
        cnt = 0;
        for(int i = 0; i < n; i++)
            for(int j = 0; j < n; j++)
                num[1][cnt++] = a[2][j] + a[3][i];//2合1;
        sort(num[1],num[1]+cnt);
        int cnt2 = cnt;
        sort(a[4],a[4]+n);
        int cnt3 = n;
        bool flag = 0;
        for(int i = 0; i < n; i++){
            int j = 0,k = cnt2-1;
            while(j<cnt1 && k>=0){
                ll temp = num[0][j]+num[1][k]+a[4][i];//3合1;
                if(temp > 0)
                    k--;
                else if(temp < 0)
                    j++;
                else {
                    flag = 1;break;
                }
            }
            if(flag)break;
        }
        if(flag)printf("Yes\n");
        else printf("No\n");
    }
    return 0;
}

 

posted @ 2015-08-25 21:12  Tobu  阅读(86)  评论(0)    收藏  举报