您的位置:首页 > 其它

51nod oj 1094 和为k的连续区间【纯暴力--二分求解】

2016-08-12 08:49 323 查看
传送门:1094

想用二分考虑一下下面的--

3 0

2 3 4

我们求的和是s[1] = 2 ;s[ 2 ] =5 ,s[ 3 ]=9

当开始没有二分查到0时,k+shu[1] = 2;

查到了2==但是其实是没有答案的--

如果能把这个问题解决掉---二分应该也会对---

二分解法已写出--以前是一个变量没写好---

在下面--

纯爆==

代码:

#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
int main()
{
LL n,k,s,shu[10010];
scanf("%lld%lld",&n,&k);
for (int i=1;i<=n;i++)
scanf("%lld",&shu[i]);
bool fafe=true;
for (int i=1;i<=n;i++)
{
s=0;
for (int j=i;j<=n;j++)
{
s+=shu[j];
if (s==k)
{
printf("%d %d\n",i,j);
fafe=false;break;
}
}
if (!fafe)break;
}
if (fafe) printf("No Solution\n");
return 0;
}


二分方法

对于上面的样例-===

在我们找到kk时,,我们从哪个点开始求和---看是否有和为k的情况--

有的话就是有解--没有继续下一个点---

代码:

#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
#define LL long long
LL shu[20100],he[20100];
LL k,s,kk;
int main()
{
int n;
scanf("%d%lld",&n,&k);
he[0]=0;
int kai,jie;
for (int i=1;i<=n;i++)
{
scanf("%lld",&shu[i]);
he[i]=he[i-1]+shu[i];
}
sort(he+1,he+1+n);
if (upper_bound(he+1,he+1+n,k)-lower_bound(he+1,he+1+n,k)>0)
{
s=0;kai=1;
for (int i=1;i<=n;i++)
{
s+=shu[i];
if (s==k)
{
jie=i;
break;
}
}
printf("%d %d\n",kai,jie);
}
else
{
bool fafe=true;
kk=k;
for (int i=1;i<n;i++)
{
kk+=shu[i];
if (upper_bound(he+1,he+1+n,kk)-lower_bound(he+1,he+1+n,kk)>0)
{
s=0;kai=i+1;
for (int j=i+1;j<=n;j++)
{
s+=shu[j];
if (s==k)
{
jie=j;
fafe=false;
break;
}
}
if(!fafe)
{
printf("%d %d\n",kai,jie);
break;
}
}
}
if (fafe) printf("No Solution\n");
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: