51nod oj 1001 1090 1267 【sort排序+二分查找 求 是否存在几个数之和为K】


题目链接:1001

题解:sort排序+二分查找

代码:

#include<cstdio>
#include<map>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL shu[50500];
int main()
{
	LL k,n;
	scanf("%lld%lld",&k,&n);
	for (int i=0;i<n;i++)
	{
		scanf("%lld",&shu[i]);
	}
	sort(shu,shu+n);
	bool fafe=true;
	for (int i=0;i<n;i++)
	{
		if (shu[i]*2>=k) break;
		LL p=k-shu[i];
		if ((upper_bound(shu,shu+n,p)-lower_bound(shu,shu+n,p))==1)
		{
		    printf("%lld %lld\n",shu[i],p);
			fafe=false;
		}
	}
	if (fafe)
	printf("No Solution\n");
	return 0;
}

题目链接:1090

与上题一样--

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL shu[1010],pp;
int main()
{
    int n;scanf("%d",&n);
    for (int i=0;i<n;i++)
        scanf("%lld",&shu[i]);
    sort(shu,shu+n);
    bool fafe=true;
    for (int i=0;i<n-2;i++)
    {
        for (int k=i+1;k<n-1;k++)
        {
            pp=-(shu[i]+shu[k]);
            if (pp>shu[k])
            {
                if (upper_bound(shu,shu+n,pp)-lower_bound(shu,shu+n,pp)==1)
                {
                    fafe=false;printf("%lld %lld %lld\n",shu[i],shu[k],pp);
                }
            }
        }
    }
    if (fafe)
        printf("No Solution\n");
    return 0;
}

题目链接: 1267


两两---两两的组合,一共最多5*10^5----

然后二分查找(N logN)--

代码:
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL shu[1020],pp;
int kp,n;
struct node{
    LL he;
    int a,b;
}dian[600000];
bool cmp(node xx,node yy)
{
	if (xx.he!=yy.he)
	return xx.he<yy.he;
	if (xx.a!=yy.a)
	return xx.a<yy.a;
	return xx.b<yy.b;
}
bool Serach(int ii,LL xx)
{
	int lp=-1;
	int L=0,R=kp-1,M;
	while (L<=R)
	{
		M=(L+R)/2;
		if (dian[M].he>=xx)
		{
			lp=M;
			R=M-1;
		}
		else
		L=M+1;
	}
	int a=dian[ii].a,b=dian[ii].b,c,d;
	if (lp!=-1)
	{
		while (dian[lp].he==xx)
		{
			c=dian[lp].a;d=dian[lp].b;
			if (a==c||a==d||b==c||b==d);
			else return true;
			lp++;
		}
	}
	return false;
}
int main()
{
    scanf("%d",&n);
    for (int i=1;i<=n;i++)
        scanf("%lld",&shu[i]);
    kp=0;
    for (int i=1;i<n;i++)
    for (int j=i+1;j<=n;j++)
    {
        dian[kp].a=i;
        dian[kp].b=j;
        dian[kp++].he=shu[i]+shu[j];
    }
    sort(dian,dian+kp,cmp);
    bool fafe=false;
	for (int i=0;i<kp;i++)
	{
		pp=-dian[i].he;
		fafe=Serach(i,pp);
		if (fafe) break;
	}
	printf("%s\n",fafe?"Yes":"No");
    return 0;
}




  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值