• 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
    ",vv[i],*it);
                else
                    printf("%lld %lld
    ",*it,vv[i]);
                *it = INF;
            }
        }
        if(!sign)
            printf("No Solution
    ");
        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
    ",-k,vv[i],*it);
                else
                    printf("%lld %lld %lld
    ",-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
    ");
        return 0;
    }
  • 相关阅读:
    从零开始~
    SVN
    了解下几个证书~~
    重要的技术发展趋势
    求职路上英语面试试题问答大全
    C语言比java重要吗?
    开源solr搜索服务器配置
    全文索引 与 Like 的实现原理
    nginx搭建多个站点
    .Solr构建索引查询索引
  • 原文地址:https://www.cnblogs.com/joeylee97/p/6258954.html
Copyright © 2020-2023  润新知