题目链接:Bound Found
Description
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做差,我们就可以对前缀和进行排序,即可获得单调性
因为最终要求区间,所以要保留排序前的下标,就用结构体存储下标和元素。
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <queue>
#include <vector>
#include <cmath>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef pair<int, int> PII;
const int N = 1e5 + 7, M = 1e5 + 7, mod = 1e9 + 7;
const int inf = 0x3f3f3f3f;
const double PI = acos(-1.0);
struct node{
int num,idx;
}pre[N];
bool cmp(node a, node b)
{
return a.num < b.num;
}
int main()
{
int n, k, t;
while (scanf("%d%d", &n, &k))
{
if (!n && !k) break;
pre[0] = {0, 0};
for (int i = 1; i <= n; i ++ )
{
int x;
scanf("%d", &x);
pre[i].num = pre[i - 1].num + x;
pre[i].idx = i;
}
sort(pre, pre + n + 1, cmp);
while (k -- )
{
int i = 0, j = 1, ans, minn = inf, l = 1, r = 1;
scanf("%d", &t);
while(j <= n && minn)
{
int temp = abs(pre[j].num - pre[i].num);
if (abs(temp - t) < minn)
{
minn = abs(temp - t);
ans = temp;
l = pre[i].idx, r = pre[j].idx;
}
if (temp > t) i ++;
if (temp < t) j ++;
if (temp == t) break;
if (i == j) j ++;
}
if (l > r) swap(l, r);
l ++;
printf("%d %d %d\n", ans, l, r);
}
}
return 0;
}