This page is still under construction.

Parts of this page are still being built. What you see may change.

Bound Found

Time limit1sMemory limit128 MB

Summary
For multiple targets, find the contiguous subarray whose absolute sum is closest to the target, reporting that absolute sum.
Level

Medium6 of 10

Topics
Prefix sum, Sorting, Binary search, Two pointers
Solved
No attempts yet

Problem

Signals believed to be of extra-terrestrial origin have been received and converted into integer data. Each signal comes in two parts: a sequence of nn integers and a non-negative integer target tt.

You are given a sequence of nn integers a1,a2,…,ana_1, a_2, \ldots, a_n and a non-negative target tt. For every non-empty contiguous subrange al,al+1,…,aua_l, a_{l+1}, \ldots, a_u (1≤l≤u≤n1 \le l \le u \le n), define its absolute sum as ∣al+al+1+⋯+au∣|a_l + a_{l+1} + \cdots + a_u|.

Among all subranges, find the one whose absolute sum is closest to tt — that is, the one minimizing ∣(absolute sum)−t∣|(\text{absolute sum}) - t| — and output that absolute sum. If two distinct absolute sums are equally close to tt, output the smaller one.

Input

The input consists of several test cases. Each test case starts with two integers nn and kk. The input is terminated by a case with n=k=0n = k = 0. Otherwise 1≤n≤1000001 \le n \le 100000, followed by the nn integers that make up the sequence, each with absolute value at most 1000010000. Then follow kk queries for this sequence; each query is a single target tt with 0≤t≤10000000000 \le t \le 1000000000.

Output

For each query, output on its own line the absolute sum of the subrange whose absolute sum is closest to tt: the value ∣al+⋯+au∣|a_l + \cdots + a_u| for a non-empty subrange that minimizes ∣(absolute sum)−t∣|(\text{absolute sum}) - t|. If two absolute sums are equally close, output the smaller one.

Examples3

  1. Example 1

    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
    
    Expected output
    5
    5
    9
    15
    15
    
  2. Example 2

    Input
    1 1
    7
    3
    0 0
    
    Expected output
    7
    
  3. Example 3

    Input
    2 1
    4 2
    5
    0 0
    
    Expected output
    4