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 0Sample Output
5 4 4 5 2 8 9 1 1 15 1 15 15 1 15给你n,k给你n个可正可负的数列,然后给你k次询问,让你求出在序列中一段连续的序列和的绝对值最接近询问值,然后输出最接近的数,以及区间范围。
记序列 a 的前缀和为 sum,则问题转化为求区间 [l, r] 使得 区间绝对值和最小 取最小值.
我们可以对 sum 排序,同时记录 sum 的原始编号.
面对这样的问题求最小值,采用尺取法即可.
AC代码:
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
#include<stdlib.h>
#include<queue>
#include<map>
#include<iomanip>
#include<math.h>
using namespace std;
typedef long long ll;
typedef double ld;
const int M = 1e5;
const int inf = 0x3f3f3f3f;
pair <int, int> sum[M + 5];
int i,j,k;
int n,m,t;
int main()
{
while(~scanf("%d %d",&n,&m)&&(n+m))
{
sum[0].first=sum[0].second=0;
for(i=1; i<=n; i++)
{
scanf("%d",&t);
sum[i].first=sum[i-1].first+t;
sum[i].second=i;
}
sort(sum,sum+n+1);
while(m--)
{
scanf("%d",&t);
int l=0,r=1;
int ans,ansl,ansr,d,dans=inf;
while(r<=n&&dans)
{
d=sum[r].first-sum[l].first;
if((int)abs(d-t)<dans)//找到最优答案
{
ans=d;
dans=(int)abs(d-t);
ansl=sum[l].second;
ansr=sum[r].second;
}
if(d>t)
++l;
else
++r;
if(l==r)
++r;
}
if(ansl>ansr)
swap(ansl,ansr);
printf("%d %d %d\n",ans,ansl+1,ansr);
}
}
return 0;
}