当前位置:   article > 正文

分治法求最大子段和_c++分治法设计最大子段和

c++分治法设计最大子段和
  1. /*
  2. 1.分治算法
  3. 2.时间复杂度不超过O(nlogn)
  4. */
  5. #include<stdio.h>
  6. #define N 50
  7. int lefts,rights;
  8. int MAXSUM(int data[],int left,int right)
  9. {
  10. int sum = 0;
  11. if(left == right)
  12. {
  13. sum = data[left]>0 ? data[left] : 0;
  14. }
  15. else
  16. {
  17. int center = (left + right)/2;
  18. int leftsum = MAXSUM(data, left, center);
  19. int rightsum = MAXSUM(data, center+1, right);
  20. int S1 = 0,LEFT = 0;//LEFT从中间往两边走
  21. for(int i = center; i >= left; i--)
  22. {
  23. LEFT += data[i];
  24. if(LEFT > S1)
  25. {
  26. S1 = LEFT;
  27. lefts = i;
  28. }
  29. }
  30. int S2 = 0,RIGHT = 0;
  31. for(int i = center+1; i <= right; i++)
  32. {
  33. RIGHT += data[i];
  34. if(RIGHT > S2)
  35. {
  36. S2 = RIGHT;
  37. rights = i;
  38. }
  39. }
  40. sum = S1 + S2;
  41. if(sum < leftsum)
  42. {
  43. sum = leftsum;
  44. lefts = left;
  45. rights = center;
  46. }
  47. if(sum < rightsum)
  48. {
  49. sum =rightsum;
  50. lefts = center+1;
  51. rights = right;
  52. }
  53. }
  54. return sum;
  55. }
  56. int main()
  57. {
  58. //输入数据
  59. int n,data[N];
  60. printf("输入元素个数:\n");
  61. scanf("%d",&n);
  62. printf("输入数据:\n");
  63. for(int i = 0; i<n; i++)
  64. {
  65. scanf("%d",&data[i]);
  66. }
  67. int left=0,right=n-1;
  68. //求最大字段和函数
  69. int sum=MAXSUM(data,left,right);
  70. printf("最大子段和为:%d\n",sum);
  71. printf("开始下标为%d,结束下标为%d",lefts,rights);
  72. }
  73. //-2 11 -4 13 -5 -2

主要算法:

        一分为二,先分别计算左边和右边的最大子段和,然后从中间往两边扩展计算最大字段和。左边、右边、从中间往两边取最大者为最大字段和!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/951913
推荐阅读
相关标签
  

闽ICP备14008679号