您的位置:首页 > 其它

51nod 1094 和为k的连续区间

2016-03-27 23:52 316 查看
一整数数列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");

}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: