二分查找。对数组每个V[i],在其中查找K-V[i],查找完成后修改v[i]避免重复输出
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstdio>
using namespace std;
typedef long long LL;
#define INF 0x3f3f3f3f
int main()
{
vector<LL> vv;
bool sign = false;
LL t,k,n;
scanf("%lld%lld",&k,&n);
for(int i=;i<n;i++)
{
scanf("%lld",&t);
vv.push_back(t);
}
sort(vv.begin(),vv.end());
int l =vv.size();
for(int i=;i<l;i++)
{
if(vv[i]==INF) continue;
vector<LL>::iterator it;
if(binary_search(vv.begin(),vv.end(),k-vv[i]))
it = lower_bound(vv.begin(),vv.end(),k-vv[i]);
else
continue;
if(it!=vv.end()&&*it!=vv[i])
{
sign = true;
if(*it>vv[i])
printf("%lld %lld\n",vv[i],*it);
else
printf("%lld %lld\n",*it,vv[i]);
*it = INF;
}
}
if(!sign)
printf("No Solution\n");
return ;
}
三个数的和为0,在前面代码基础上略作修改即可。
#include<iostream>
#include<algorithm>
#include<vector>
#include<cstring>
#include<cstdio>
using namespace std;
typedef long long LL;
#define MAXN 1001
#define INF 0x3f3f3f3f
bool been[MAXN];
bool all_sign = false;
LL n;
vector<LL> VV;
void solve(LL k,vector<LL> vv,LL pos)
{
memset(been,false,sizeof(been));
for(LL i=pos+;i<n;i++)
{
if(been[i]==true) continue;
vector<LL>::iterator it;
if(binary_search(vv.begin()+pos+,vv.end(),k-vv[i]))
it = lower_bound(vv.begin()+pos+,vv.end(),k-vv[i]);
else
continue;
if(it!=vv.end()&&*it!=vv[i])
{
all_sign = true;
if(*it>vv[i])
printf("%lld %lld %lld\n",-k,vv[i],*it);
else
printf("%lld %lld %lld\n",-k,*it,vv[i]);
been[it-vv.begin()] = true;
}
} }
int main()
{
LL temp,i;
scanf("%lld",&n);
for(i=;i<n;i++)
{
scanf("%lld",&temp);
VV.push_back(temp);
}
sort(VV.begin(),VV.end());
for(i=;i<n;i++)
{
if(VV[i]>=)
break;
temp = VV[i];
solve(-temp,VV,i);
been[i] = true;
}
if(!all_sign)
printf("No Solution\n");
return ;
}