标签:
4 6 -4 5 6 2 -1 1
1 0
这个题一开始思考有没有O(n)的办法,结果并没有找到很好的办法
于是只好按O(n2)的办法做,试着提交,居然没超时
代码如下
1 #include <cstdio> 2 #include <cstdlib> 3 #include <cmath> 4 #include <cstring> 5 int n; 6 typedef long long ll; 7 int num[100002]; 8 ll sum[100002]; 9 10 int main(int argc, char const *argv[]) 11 { 12 while(scanf("%d",&n) != EOF) { 13 sum[0] = 0; 14 for(int i = 1; i <= n; i++) { 15 scanf("%d",&num[i]); 16 sum[i] = sum[i-1] + num[i]; 17 } 18 int min = 999999999; 19 for(int i = n; i >= 1 && min != 0; i--) { 20 for(int j = i-1; j >= 0 && min != 0; j--) { 21 ll tmp = sum[i] - sum[j]; 22 if(abs(tmp) < abs(min)) { 23 min = tmp; 24 } 25 if(abs(tmp) == abs(min)) { 26 if(tmp >= 0) { 27 min = tmp; 28 } 29 } 30 if(min == 0) { 31 break; 32 } 33 } 34 } 35 printf("%d\n",min); 36 } 37 return 0; 38 } 39 40 //6 -4 5 6 41 //6 2 7 13
标签:
原文地址:http://www.cnblogs.com/jasonJie/p/5811540.html