Bound Found
Signals of most probably extra-terrestrial origin have been received and digitalized by The Aeronautic and Space Administration (that must be going through a defiant phase: "But I want to use feet, not meters!"). Each signal seems to come in two parts: a sequence of n integer values and a non-negative integer t. We'll not go into details, but researchers found out that a signal encodes two integer values. These can be found as the lower and upper bound of a subrange of the sequence whose absolute value of its sum is closest to t.
You are given the sequence of n integers and the non-negative target t. You are to find a non-empty range of the sequence (i.e. a continuous subsequence) and output its lower index l and its upper index u. The absolute value of the sum of the values of the sequence from the l-th to the u-th element (inclusive) must be at least as close to t as the absolute value of the sum of any other non-empty range.
Input
The input file contains several test cases. Each test case starts with two numbers n and k. Input is terminated by n=k=0. Otherwise, 1<=n<=100000 and there follow n integers with absolute values <=10000 which constitute the sequence. Then follow k queries for this sequence. Each query is a target t with 0<=t<=1000000000.
Output
For each query output 3 numbers on a line: some closest absolute sum and the lower and upper indices of some range where this absolute sum is achieved. Possible indices start with 1 and go up to n.
Sample Input
5 1 -10 -5 0 5 10 3 10 2 -9 8 -7 6 -5 4 -3 2 -1 0 5 11 15 2 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 15 100 0 0
Sample Output
5 4 4 5 2 8 9 1 1 15 1 15 15 1 15
题意:求 和的绝对值最接近t的区间
既然要找到一个子区间使得和最接近t的话,那么不断地找比当前区间的和更大的区间,如果区间和已经大于等于t了,那么不需要在去找更大的区间了,因为其和与t的差值更大,然后区间左端点向右移动推进即可。所以,首先根据计算出所有的区间和,
排序之后按照上面的思路求解即可。
#include <algorithm>
#include <cstring>
#include <cstdio>
#include <cmath>
using namespace std;
#define ll long long
const int INF = 0x3f3f3f3f;
const int N = 1e5 + 7;
struct S {
ll sum, id;
bool operator< (const S& a) const {
if (sum == a.sum) return id < a.id;
return sum < a.sum;
}
} sum[N];
ll a[N];
template<typename T>
T myabs(T x) {
return x > 0 ? x : -x;
}
int main() {
int n, k;
while (~scanf ("%d %d", &n, &k) && (n + k)) {
sum[0].sum = 0, sum[0].id = 0;
for (int i = 1; i <= n; ++i) {
scanf ("%lld", &a[i]);
sum[i].sum = sum[i-1].sum + a[i];
sum[i].id = i;
}
sort(sum, sum+n+1);
while (k--) {
ll t;
scanf ("%lld", &t);
int tail = 0, head = 1, l = 0, r = 0;
ll sum1 = 0, ans, tmp = INF;
while (head <= n) {
sum1 = sum[head].sum - sum[tail].sum;
if (myabs(t - sum1) < tmp) {
tmp = myabs(t - sum1);
ans = sum1, r = sum[head].id, l = sum[tail].id;
}
if (sum1 < t) ++head;
else if (sum1 > t) ++tail;
else break;
if (head == tail) ++head;
}
if (l > r) swap(l, r);
printf ("%lld %d %d\n", ans, l+1, r);
}
}
return 0;
}
本文介绍了一种算法,用于解决给定序列中找到一个子区间的问题,该子区间的和的绝对值最接近指定的目标值。通过预计算所有可能的子区间和并进行排序,可以有效地找到最佳子区间。
794

被折叠的 条评论
为什么被折叠?



