51nod 1094 和为k的连续区间

一整数数列a1, a2, ... , an(有正有负),以及另一个整数k,求一个区间[i, j],(1 <= i <= j <= n),使得a[i] + ... + a[j] = k。
Input
第1行:2个数N,K。N为数列的长度。K为需要求的和。(2 <= N <= 10000,-10^9 <= K <= 10^9)
第2 - N + 1行:A[i](-10^9 <= A[i] <= 10^9)。
Output
如果没有这样的序列输出No Solution。
输出2个数i, j,分别是区间的起始和结束位置。如果存在多个,输出i最小的。如果i相等,输出j最小的。
Input示例
6 10
1
2
3
4
5
6
Output示例
1 4



思路:二分



#include <iostream>
#include <cstring>
#include <cstdlib>
#include <cstdio>
#include <string>
#include <cmath>
#include <set>
#include <queue>
#include <algorithm>
#include <vector>
#include <map>
using namespace std;
#define esp  1e-8
const double PI = acos(-1.0);
const int inf = 1000000005;
const long long mod = 1000000007;
//freopen("in.txt","r",stdin); //输入重定向,输入数据将从in.txt文件中读取
//freopen("out.txt","w",stdout); //输出重定向,输出数据将保存在out.txt文件中
struct node
{
	long long x;
	int id;
}a[10005];
long long b[10005];
bool cmp(node a, node b)
{
	if (a.x == b.x)
		return a.id < b.id;
	return a.x < b.x;
}
int main()
{
	int n, k, i, j;
	while (~scanf("%d%d", &n, &k))
	{
		a[0].x = 0;
		b[0] = 0;
		int ans = 0;
		for (i = 1; i <= n; ++i)
		{
			scanf("%lld", &a[i].x);
			a[i].x += a[i - 1].x;
			a[i].id = i;
			b[i] = a[i].x;
		}
		sort(a + 1, a + 1 + n, cmp);
		int xx, yy;

		for (i = 1; i <= n; ++i)
		{
			//printf("%lld %d\n", a[i].x, a[i].id);
			long long p = k + b[i - 1];
			int l = 1, r = n;
			while (l <= r)
			{
				int mid = (l + r) / 2;
				if (a[mid].x > p)
					r = mid - 1;
				else if (a[mid].x < p)
					l = mid + 1;
				else if(a[mid].x == p)
				{
					if (a[mid].id >= i)
					{
						ans = 1;
						xx = i;
						yy = a[mid].id;
						break;
					}
					else
						l++;
					
				}
			}
			if (ans)
				break;
		}
		if (ans)
			printf("%d %d\n", xx, yy);
		else
			printf("No Solution\n");

	}
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值