Sumsets(4sum问题)

梦里梦外; 2022-08-01 18:06 258阅读 0赞

Sumsets














Time Limit: 1000MS   Memory Limit: 65536K
Total Submissions: 8954   Accepted: 2465

Description

2549_1.jpgGiven S, a set of integers, find the largest d such that a + b + c = d where a, b, c, and d are distinct elements of S.

Input

Several S, each consisting of a line containing an integer 1 <= n <= 1000 indicating the number of elements in S, followed by the elements of S, one per line. Each element of S is a distinct integer between -536870912 and +536870911 inclusive. The last line of input contains 0.

Output

For each S, a single line containing d, or a single line containing “no solution”.

Sample Input

  1. 5
  2. 2
  3. 3
  4. 5
  5. 7
  6. 12
  7. 5
  8. 2
  9. 16
  10. 64
  11. 256
  12. 1024
  13. 0

Sample Output

  1. 12
  2. no solution

Source

Waterloo local 2001.06.02

这里是4sum问题或者说3sum问题求和(和是变量多了一重循

环)

正常是四重循环,这样做一定会超时的!

这里用的是三重循环,其中第三重循环是用2sum问题实现的!

  1. #include<cstdio>
  2. #include<algorithm>
  3. #include<iostream>
  4. #include<cstring>
  5. using namespace std;
  6. int a[1005];
  7. int main()
  8. {
  9. int n,i,j,t,l,r,flag;
  10. while(cin>>n&&n)
  11. {
  12. for(i=0;i<n;i++)
  13. {
  14. cin>>a[i];
  15. }
  16. sort(a,a+n);
  17. flag=0;
  18. for(i=n-1;i>=0;i--)
  19. {
  20. for(j=n-1;j>=0;j--)
  21. {
  22. if(i!=j)
  23. {
  24. t=a[i]-a[j];
  25. for(l=0,r=j-1;l<r;)
  26. {
  27. if(a[l]+a[r]==t)
  28. {
  29. flag=1;
  30. break;
  31. }
  32. else if(a[l]+a[r]>t)
  33. {
  34. r--;
  35. }
  36. else
  37. {
  38. l++;
  39. }
  40. }
  41. if(flag)
  42. {
  43. break;
  44. }
  45. }
  46. }
  47. if(flag)
  48. {
  49. break;
  50. }
  51. }
  52. if(flag)
  53. {
  54. cout<<a[i]<<endl;
  55. }
  56. else
  57. {
  58. cout<<"no solution"<<endl;
  59. }
  60. }
  61. }

发表评论

表情:
评论列表 (有 0 条评论,258人围观)

还没有评论,来说两句吧...

相关阅读

    相关 18 4Sum

    类似的题目有 [1 TwoSum][] [15 3Sum][] [16 3Sum Closest][] 第一次使用的是笨办法,四层嵌套for循环,总是超时