POJ_2566_前缀和&&尺取法

来源:互联网 发布:许小年水平怎么样知乎 编辑:程序博客网 时间:2024/04/30 04:49

Bound Found
Time Limit: 5000MS Memory Limit: 65536KTotal Submissions: 3949 Accepted: 1219 Special Judge

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 10310 2-9 8 -7 6 -5 4 -3 2 -1 05 1115 2-1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -115 1000 0

Sample Output

5 4 45 2 89 1 115 1 1515 1 15

给出一个含有 N 个元素的整数数列,再给出 K 个正整数 t。对于每个 t, 求数列的一个连续区间,使区间和的绝对值最接近 t。依次输出区间和,左界,右界。


首先求出出各项的前缀和,注意要上一个额外项 (0, 0)。

前缀和序列中任意两项的差都代表一个子序列的和,其中和(0,0)的查表示从0开始的子序列的和。

将前缀和数组排序,这样就可以用尺取法解决了。

指针移动条件:

当前和小于 t 时,右指针右移动。当前和大于 t 时,左指针右移。

更新答案条件:

当前和与 t 的绝对值之差小于已有值时,更新 ans, l, r。


#include<cstdio>#include<iostream>#include<algorithm>#include<cstdlib>#define f(x) p[x].first#define s(x) p[x].secondusing namespace std;typedef pair<int, int> P;const int maxn = 100000;int a[maxn + 10];P p[maxn + 10];int N, K;void solve(int x){int i = 0, j = 1;int l = s(i), r = s(j);int ans = f(j) - f(i), dis = abs(ans - x);while(j <= N && dis != 0){//计算状态int t = f(j) - f(i);int d = abs(t - x);//更新答案if(d < dis) dis = d, ans = t, l = s(i), r = s(j);//移动首尾指针if(t < x) j ++;if(t > x) i ++;if(i == j) j++;}if(l > r) swap(l, r);cout << ans << " " << l+1 << " " << r << endl;}int main (){while(1){cin >> N >> K;if(N == 0) break;int sum = 0;f(0) = s(0) = 0;for(int i= 1; i<= N; i++){int t;cin >> t;sum += t;f(i) = sum, s(i) = i;}sort(p, p+N+1);while(K--){int t;cin >> t;solve(t);}}return 0;}


0 0
原创粉丝点击