当前位置:   article > 正文

【算法设计与分析】最大子段和问题_分别用蛮力法、分冶法和动态规划法设计最大子段和问题的算法,并设计测试数据,比较

分别用蛮力法、分冶法和动态规划法设计最大子段和问题的算法,并设计测试数据,比较

 一、实验题目:

给定由n个整数组成的序列(a_{1},a_{2},a_{3} …… a_{n}……a_{n}),求该序列形如\sum_{k=i}^{j}a_{k}的子段和的最大值,当所有整数均为负整数时,其最大子段和为0

二、实验要求:

1)分别用蛮力法、分治法和动态规划法设计最大子段和问题的算法;

2)比较不同算法的时间性能;

3)给出测试数据,写出程序文档。

三、实验代码

  1. // 实验2.1最大字段和问题.cpp : 此文件包含 "main" 函数。程序执行将在此处开始并结束。
  2. #include <iostream>
  3. using namespace std;
  4. //最大字段和:蛮力法
  5. int MaxSum_Manli(int a[], int n){
  6. int sum, maxSum;
  7. sum = 0;
  8. maxSum = 0;
  9. int i, j, k;
  10. for (i = 0; i < n; i++) {
  11. for (j = i; j < n; j++){
  12. sum = 0;
  13. for (k = i; k <= j; k++)
  14. sum += a[k];
  15. if (sum > maxSum)
  16. maxSum = sum;
  17. }
  18. }
  19. return maxSum;
  20. }
  21. //最大字段和:分治法实现
  22. int MaxSum_Fenzhi(int a[], int left, int right) {
  23. int sum = 0, midSum = 0, leftSum = 0, rightSum = 0, i, j;
  24. int center, s1, s2, lefts, rights;
  25. if (left == right) //如果序列长度为1,直接求解
  26. sum = a[left];
  27. else {
  28. center = (left + right) / 2; //划分
  29. leftSum = MaxSum_Fenzhi(a, left, center); //对应情况①,递归求解
  30. rightSum = MaxSum_Fenzhi(a, center + 1, right); //对应情况②,递归求解
  31. s1 = 0; lefts = 0; //以下对应情况③,先求解s1
  32. for (i = center; i >= left; i--){
  33. lefts += a[i];
  34. if (lefts > s1) s1 = lefts;
  35. }
  36. s2 = 0; rights = 0; //再求解s2
  37. for (j = center + 1; j <= right; j++){
  38. rights += a[j];
  39. if (rights > s2) s2 = rights;
  40. }
  41. midSum = s1 + s2; //计算情况③的最大子段和
  42. if (midSum < leftSum) sum = leftSum; //合并解,取较大者
  43. else sum = midSum;
  44. if (sum < rightSum) sum = rightSum;
  45. }
  46. return sum;
  47. }
  48. //最大字段和:动态规划法
  49. int MaxSum_Dongtai(int a[], int n){
  50. int sum, maxSum;
  51. int i;
  52. sum = 0;
  53. maxSum = 0;
  54. for (i = 0; i < n; i++) {
  55. sum += a[i];
  56. if (sum > maxSum)
  57. maxSum = sum;
  58. else if (sum < 0)
  59. sum = 0;
  60. }
  61. return maxSum;
  62. }
  63. int main(){
  64. int a[100] = { 2,11,-4,13,-5,-2,20 };
  65. int n = 7;
  66. cout << "请输入数字串个数:";
  67. cin >> n;
  68. cout << "请依次输入 " << n << " 个数字:";
  69. for (int i = 0; i < n; i++) {
  70. cin >> a[i];
  71. }
  72. cout << endl;
  73. int sum1 = MaxSum_Manli(a, n);
  74. int sum2 = MaxSum_Fenzhi(a, 0, n-1);
  75. int sum3 = MaxSum_Dongtai(a, n);
  76. cout << "使用蛮力法求得:" << sum1 << endl;
  77. cout << "使用分治法求得:" << sum2 << endl;
  78. cout << "使用动态规划法求得:" << sum3 << endl;
  79. }

四、运行结果:

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

闽ICP备14008679号