(HDU - 4334)Trouble

(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;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值