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
题意:给了长度为n的序列,k次询问,每次询问给定一个数 t ,问在整个序列中 哪一段的子序列的和 的绝对值最接近t,并输出区间下标。
思路:因为是求某段子序列,而且还是子序列和的绝对值,所以我们可以先求一下前缀和,并记录位置。那么此时我们取任意两个前缀和的值相减 得到的结果就是一段子序列和,又因为是求绝对值,所以我们不用在意序列的前后。因此我们可以先对前缀和进行从小到大的排序,然后通过动态的尺取法(以子序列和的绝对值 与 t 的 差值 的绝对值作为尺),动态维护最小插值,并记录大小与下标。
代码如下:
#include<cstdio>
#include<cstring>
#include<algorithm>
#define inf 999999999999
#define N 100010
#define ll long long
using namespace std;
struct node
{
ll a;
int bit;
} eg[N];
ll abss(ll x)
{
if(x<0)return -x;
return x;
}
bool cmp(node x,node y)
{
return x.a<y.a;
}
int main()
{
int n,q;
while(~scanf("%d%d",&n,&q)&&(n||q))
{
eg[0].a=eg[0].bit=0;
for(int i=1; i<=n; i++)
{
ll x;
scanf("%lld",&x);
eg[i].a=eg[i-1].a+x; //前缀和
eg[i].bit=i; //记录下标
}
sort(eg,eg+n+1,cmp);//排序
while(q--)
{
ll t;
scanf("%lld",&t);
int l=0,r=1,la,lb;
ll minn=inf,ans;
while(r<=n&&minn)
{
ll sum=abss(eg[r].a-eg[l].a); //某段子序列和的绝对值
if(abss(sum-t)<minn) //动态维护sum和t的差值
{
minn=abss(sum-t);
ans=sum; //记录值和下标
la=eg[r].bit;
lb=eg[l].bit;
}
if(sum>t) //如果绝对值大于t 则需要使绝对值变小一点,所以 l++
l++;
if(sum<t) //同理,
r++;
if(l==r) //同一个点的话 r++继续维护
r++;
}
if(la>lb) //下标交换
swap(la,lb);
printf("%lld %d %d\n",ans,la+1,lb);
}
}
}