(HDU

来源:互联网 发布:邮电大学网络教育 编辑:程序博客网 时间:2024/06/16 20:45

(HDU - 4334)Trouble

Time Limit: 10000/5000 MS (Java/Others) Memory Limit: 32768/32768 K (Java/Others)
Total Submission(s): 6218 Accepted Submission(s): 1738

Problem Description

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

题目大意:在5个集合中分别取一个数使这5个数的和为0。

思路:这题刚开始我想到的是二分,因为这题就是典型的二分,先预处理出前三个集合的和,后两个集合的和,然后二分查找,时间复杂度为O(n3logn)。再看了大佬的思路后,发现了一种更好的方法,先利用分治思想,处理前两个集合的和sum1,3 4集合的和sum2。然后要介绍一种尺取法(也就是一种贪心思想):如何快速判断是否有A[i]+B[j]=x,先将A,B送小到大排序得到有序序列,可以先让i指向A数组的首指针,j指向B数组的为指针,判断A[i]+B[j]与x的大小关系,若A[i]+B[j]>x则j–;若A[i]+B[j]< x则i++。这样就可以在线性时间内判断是否有A[i]+B[j]=x。利用这种方法最后的复杂度为O(n3)。显然选择这种方法更好。

#include<cstdio>#include<algorithm>using namespace std;typedef long long LL;const int maxn=205;LL a[5][maxn];LL sum1[maxn*maxn],sum2[maxn*maxn];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("%lld",&a[i][j]);        int k=0;        for(int i=0;i<n;i++)            for(int j=0;j<n;j++) sum1[k++]=a[0][i]+a[1][j];        k=0;        for(int i=0;i<n;i++)            for(int j=0;j<n;j++) sum2[k++]=a[2][i]+a[3][j];        sort(sum1,sum1+k);        sort(sum2,sum2+k);        bool flag=false;        for(int i=0;i<n&&!flag;i++)        {            int l=0,r=k-1;            while(l<k&&r>=0)            {                if(sum1[l]+sum2[r]==-a[4][i])                {                    flag=true;                    break;                }                else if(sum1[l]+sum2[r]>-a[4][i]) r--;                else l++;            }        }        if(flag) printf("Yes\n");        else printf("No\n");    }    return 0;}
原创粉丝点击