https://www.51nod.com/onlineJudge/questionCode.html#!problemId=1090&judgeId=579502
基准时间限制:1 秒 空间限制:131072 KB 分值: 5 难度:1级算法题
收藏
关注
给出一个长度为N的无序数组,数组中的元素为整数,有正有负包括0,并互不相等。从中找出所有和 = 0的3个数的组合。如果没有这样的组合,输出No Solution。如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则按照第二小的数排序。
Input
第1行,1个数N,N为数组的长度(0 <= N <= 1000) 第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)
Output
如果没有符合条件的组合,输出No Solution。 如果有多个,按照3个数中最小的数从小到大排序,如果最小的数相等则继续按照第二小的数排序。每行3个数,中间用空格分隔,并且这3个数按照从小到大的顺序排列。
Input示例
7 -3 -2 -1 0 1 2 3
Output示例
-3 0 3 -3 1 2 -2 -1 3 -2 0 2 -1 0 1
暴力解决能过......
#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<map>
#include<math.h>
#include<stack>
#define inf 0x3f3f3f
#define ll long long
#define maxn 100000
using namespace std;
int a[1200];
int main()
{
int n;
cin>>n;
int flag=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
if(a[i]+a[j]<=0)
{
for(int k=j+1;k<n;k++)
{
if(a[i]+a[j]+a[k]==0)
{
cout<<a[i]<<" "<<a[j]<<" "<<a[k]<<endl;
flag=1;
}
}
}
}
}
if(flag==0)
cout<<"No Solution"<<endl;
return 0;
}
二分法
#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<map>
#include<math.h>
#include<stack>
#define inf 0x3f3f3f
#define ll long long
#define maxn 100000
using namespace std;
ll a[1200];
struct node
{
int x;
int y;
int z;
}temp;
vector<node>ans;
int quik_sort(int q,int w,int e)
{
int l=q,r=w,mid;
while(l<=r)
{
mid=(l+r)/2;
if(e>a[mid])
l=mid+1;
else if(e<a[mid])
r=mid-1;
else
return 1;
}
return 0;
}
int main()
{
int n;
cin>>n;
int flag=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
int sum=-(a[i]+a[j]);
if(quik_sort(j+1,n-1,sum))
{
cout<<a[i]<<" "<<a[j]<<" "<<sum<<endl;
flag=1;
}
}
}
if(flag==0)
cout<<"No Solution"<<endl;
return 0;
}
lower-bound :https://www.cnblogs.com/cobbliu/archive/2012/05/21/2512249.html
#include<iostream>
#include<string.h>
#include<algorithm>
#include<vector>
#include<stdio.h>
#include<map>
#include<math.h>
#include<stack>
#define inf 0x3f3f3f
#define ll long long
#define maxn 100000
using namespace std;
ll a[1200];
struct node
{
int x;
int y;
int z;
}temp;
vector<node>ans;
int main()
{
int n;
cin>>n;
int flag=0;
for(int i=0;i<n;i++)
{
cin>>a[i];
}
sort(a,a+n);
for(int i=0;i<n;i++)
{
for(int j=i+1;j<n;j++)
{
ll sum=-(a[i]+a[j]);
int pos=lower_bound(a+j+1,a+n,sum)-a;
if(pos>=n||a[pos]!=sum) continue;
temp.x=a[i];temp.y=a[j];
temp.z=sum;
ans.push_back(temp);
}
}
if(ans.size()==0)
cout<<"No Solution"<<endl;
else
{
for(int i=0;i<ans.size();i++)
cout<<ans[i].x<<" "<<ans[i].y<<" "<<ans[i].z<<endl;
}
return 0;
}