1001 数组中和等于K的数对 1090 3个数和为0

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1001 数组中和等于K的数对 1090 3个数和为0相关的知识,希望对你有一定的参考价值。

二分查找。对数组每个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=0;i<n;i++)
    {
        scanf("%lld",&t);
        vv.push_back(t);
    }
    sort(vv.begin(),vv.end());
    int l =vv.size();
    for(int i=0;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;
}

三个数的和为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+1;i<n;i++)
    {
        if(been[i]==true) continue;
        vector<LL>::iterator it;
        if(binary_search(vv.begin()+pos+1,vv.end(),k-vv[i]))
            it = lower_bound(vv.begin()+pos+1,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=0;i<n;i++)
    {
        scanf("%lld",&temp);
        VV.push_back(temp);
    }
    sort(VV.begin(),VV.end());
    for(i=0;i<n;i++)
    {
        if(VV[i]>=0)
            break;
        temp = VV[i];
        solve(-temp,VV,i);
        been[i] = true;
    }
    if(!all_sign)
        printf("No Solution\n");
    return 0;
}

 

以上是关于1001 数组中和等于K的数对 1090 3个数和为0的主要内容,如果未能解决你的问题,请参考以下文章

1001 数组中和等于K的数对 (51nod)

51 nod 1001 数组中和等于K的数对

1001 数组中和等于K的数对

[51nod]1001 数组中和等于K的数对

51nod 1001 数组中和等于k的数对

51Nod - 1001 数组中和等于K的数对 (排序+ 尺取)