POJ 2566 尺取
- 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的子序列,输出这段子序列的和的绝对值,和序列的区间 [ 1 , n ]。
- 思路:自己先写一个结构体,然后里面两个变量,id 和 sum,id存第 i 个输入,然后sum求第一个输入的数到 i 的和。然后把结构体从小到大排序,用尺取来求子序列,比如a1(1,3)和a3(3,5),a3.sum-a1.sum就代表 2 -> 3 这个序列的和,有一点需要注意,就是有可能刚好从1->id就是正确答案,所以需把a[0].id=0;a[0].sum=0;
#include<iostream>
#include<algorithm>
#include<cstdio>
#include<cmath>
using namespace std;
const int maxn = 1e5+50;
const int inf = 0x3f3f3f3f;
int n,k,x,t,i,j,sum,ans,sub;
int l,r;
struct Node{
int id;
int sum;
};
bool cmp(Node x,Node y){
return x.sum<y.sum;
}
int main(){
while(scanf("%d%d",&n,&k)&&(k!=0||n!=0)){
Node a[maxn];
a[0].sum=0;a[0].id=0;
for(int m=1;m<=n;m++){
scanf("%d",&x);
a[m].sum=a[m-1].sum+x;
a[m].id=m;
}
sort(a,a+n+1,cmp);
while(k--){
scanf("%d",&t);
i=0;
j=1;
sum=ans=0;
sub=inf;
l=r=0;
while(j<=n){
sum=a[j].sum-a[i].sum;//因为总是大减小,所以sum总是正的
if(abs(sum-t)<sub){
l=min(a[i].id,a[j].id);
r=max(a[i].id,a[j].id);
sub=abs(sum-t);
ans=sum;
}
if(sum<t)j++;//如果和比t小了,就j右移
else if(sum>t)i++;//反之左移
else break;//sum==t就不需要往下找了
if(i==j)j++;//如果i右移到和j相等
}
l++;//因为l取的是左端点的前一个点的id,所以要往右移一下
printf("%d %d %d\n",ans,l,r);
}
}
}