0
点赞
收藏
分享

微信扫一扫

1090 3个数和为0


1090 3个数和为0

给出一个长度为N的无序数组,数组中的元素为整数,有正有负包括0,并互不相等。从中找出所有和 = 0的3个数的组合。如果没有这样的组合,输出No Solution。如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则按照第二小的数排序。

 收起

输入


第1行,1个数N,N为数组的长度(0 <= N <= 1000) 第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)


输出


如果没有符合条件的组合,输出No Solution。 如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则继续按照第二小的数排序。每行3个数,中间用空格分隔,并且这3个数按照从小到大的顺序排列。


输入样例


7 -3 -2 -1 0 1 2 3


输出样例


-3 0 3 -3 1 2 -2 -1 3 -2 0 2 -1 0 1


思路 : 

1090 3个数和为0_#include

 会超时,转化为 

1090 3个数和为0_#include_02

 。先从小到大排好序, 然后 

1090 3个数和为0_i++_03

  枚举数组, 找使 3 个数和为 0 的问题转换成查找 是否存在 -(a[i]+a[j]) 的问题。

 

#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std ;
typedef long long LL;
const LL inf = 0x3f3f3f3f3f3f3f3f;
// 1014
const LL maxn = 1e18+999 ;
const int MAX = 10010 ;
int n ;
LL a[MAX] ;
bool Find(LL x , int p ) {

int l = p , r = n ;
while(l<=r) {
int mid = (l+r)/2 ;
if(a[mid] == x){
return 1 ;
}
else if(a[mid] < x ) {
l = mid + 1 ;
}
else {
r = mid -1 ;
}
}

return 0 ; // 没找到
}
int main() {
bool flag = false ;
cin >> n ;
for(int i = 1 ; i <=n ;i++) {
scanf("%lld",&a[i]) ;
}
sort(a+1,a+1+n) ;
for(int i = 1 ; i<=n;i++) {
for(int j = i+1 ; j<=n ; j++ ) {
LL x = -(a[i]+a[j]) ;
bool s = Find(x,j+1); // 看能不能找到
if(s) {
flag = true ;
printf("%lld %lld %lld\n",a[i],a[j] ,x ) ;
}
}
}
if(!flag) {
printf("No Solution") ;
}
return 0 ;
}

 

举报

相关推荐

0 条评论