fork(2) download
  1. #include<stdio.h>
  2.  
  3. #define wb(x) ((x)<0?-(x):(x))
  4.  
  5. int coord[20], pos[1<<16];
  6. long long min[1<<16], max[1<<16];
  7.  
  8. int main()
  9. {
  10. int n, d, i, j, k, m, a, b;
  11. long long x;
  12.  
  13. scanf("%d%d", &d, &n);
  14. m = 1<<(d-1); // 2^(d-1)
  15. for(i = 0; i < m; ++i) // preprocessing; calculating all positions on which Gray numbers change
  16. {
  17. min[i] = 1e15;
  18. max[i] = -1e15;
  19. if(i)
  20. {
  21. pos[i] = 1; a = i^(i>>1); b = (i-1)^((i-1)>>1); k = a^b; // formulas for n-th Gray numbers
  22. while(k%2 == 0) // given power of 2 calculates the exponent
  23. ++pos[i],
  24. k >>= 1;
  25. if(b < a) // negative numbers for change from bit 1 to 0
  26. pos[i] = -pos[i];
  27. }
  28. }
  29. while(n--)
  30. {
  31. for(j = 0; j < d; ++j)
  32. scanf("%d", &coord[j]);
  33. x = 0;
  34. for(k = 0; k < d; ++k) // calculate the first sum
  35. x += coord[k];
  36. if(x < min[0])
  37. min[0] = x;
  38. if(x > max[0])
  39. max[0] = x;
  40. for(j = 1; j < m; ++j) // check all combinations of sums
  41. {
  42. x += 2*coord[wb(pos[j])-1]*(pos[j] > 0 ? 1 : -1); // add or subtract one element
  43. if(x < min[j])
  44. min[j] = x;
  45. if(x > max[j])
  46. max[j] = x;
  47. }
  48. }
  49. x = -1;
  50. for(i = 0; i < m; ++i)
  51. if(wb(max[i]-min[i]) > x)
  52. x = wb(max[i]-min[i]);
  53. printf("%lld\n", x);
  54. return 0;
  55. }
Success #stdin #stdout 0s 3532KB
stdin
4 3
10 -3 -2 5
1 2 3 4
-1 2 0 4
stdout
20