Bound Found POJ - 2566
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
Output
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
1.好题~~~虽然没做出来!
2.取数组的前缀和再排序再尺取。
3.关键在于转换
1 #include<iostream> 2 #include<algorithm> 3 #include<cmath> 4 #include<cstdio> 5 #include<cstring> 6 using namespace std; 7 8 struct node{ 9 int sum,id; 10 bool operator <(const node& i)const{ 11 return sum<i.sum; 12 } 13 }a[100005]; 14 15 int n,m; 16 17 void query(int t){ 18 int l=0,r=1,mid=2000000000; //初始l和r,没有长度为0的区间! 19 int ans,ansl,ansr; 20 while(r<=n){ 21 int temp=a[r].sum-a[l].sum; 22 if(abs(temp-t)<mid){ 23 mid=abs(temp-t); 24 ans=temp; 25 ansl=a[l].id; 26 ansr=a[r].id; 27 } 28 if(temp>t) l++; 29 else if(temp<t) r++; 30 else break; 31 if(l==r) r++; 32 } 33 if(ansl>ansr) swap(ansl,ansr); 34 printf("%d %d %d\n",ans,ansl+1,ansr); 35 } 36 37 int main() 38 { int x; 39 while(~scanf("%d%d",&n,&m),n||m){ 40 a[0].id=0,a[0].sum=0; 41 for(int i=1;i<=n;i++){ 42 scanf("%d",&x); 43 a[i].sum=a[i-1].sum+x; 44 a[i].id=i; 45 } 46 sort(a,a+n+1); //一定要包括a[0]! 47 while(m--){ 48 int q;scanf("%d",&q); 49 query(q); 50 } 51 } 52 return 0; 53 }