Time Limit: 5000MS | Memory Limit: 65536K | |||
Total Submissions: 1445 | Accepted: 487 | Special Judge |
Description
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
Source
1 #include <iostream> 2 #include <cstdio> 3 #include <cstring> 4 #include <algorithm> 5 #include <cmath> 6 7 using namespace std; 8 9 #define maxn 100005 10 #define INF 2000000000 11 12 typedef pair<int,int> pii; 13 14 int n,k; 15 pii a[maxn]; 16 17 int Abs(int x) { 18 return x > 0 ? x : -x; 19 } 20 21 22 void solve(int x) { 23 int sum = 0,s = 0,pos = 1,v,ans = INF,l,r; 24 //printf("ans = %d\n",ans); 25 for(; s <= n && pos <= n;) { 26 int tem = a[pos].first - a[s].first; 27 //printf("tem = %d\n",tem); 28 if( Abs(tem - x) < ans) { 29 ans = Abs(tem - x); 30 l = a[s].second; 31 r = a[pos].second; 32 v = tem; 33 } 34 35 if(tem > x) { 36 ++s; 37 } else if(tem < x) { 38 ++pos; 39 } else { 40 break; 41 } 42 if(s == pos) ++pos; 43 44 } 45 if(l > r) swap(l,r); 46 47 printf("%d %d %d\n",v,l + 1,r); 48 } 49 50 51 52 int main() { 53 // freopen("sw.in","r",stdin); 54 55 while(~scanf("%d%d",&n,&k) ) { 56 if(!n && !k) break; 57 int sum = 0; 58 a[0] = pii(0,0); 59 for(int i = 1; i <= n; ++i) { 60 int ch; 61 scanf("%d",&ch); 62 sum += ch; 63 a[i] = make_pair(sum,i); 64 65 } 66 67 sort(a,a + n + 1); 68 69 for(int i = 1; i <= k; ++i) { 70 int t; 71 scanf("%d",&t); 72 solve(t); 73 } 74 75 } 76 return 0; 77 }
原文:http://www.cnblogs.com/hyxsolitude/p/3631980.html