[关闭]
@rg070836rg 2015-11-17T23:41:32.000000Z 字数 1040 阅读 1380

算法概论实验五

算法概论实验


  1. 实验五
  2. 实验目的与要求:掌握动态规划方法的基本思想与设计策略。
  3. 1.最长递增子序列问题
  4. 【问题描述】
  5. 给定一个整数数组,设计一个动态规划算法求出该数组中的最长递增子序列。
  6. 2.矩阵连乘问题
  7. 【问题描述】
  8. 给定n个矩阵{A1A2,…,An},其中AiAi+1是可乘的,i=12,…,n-1,考察这n个矩阵的连乘积A1A2An,设计一个动态规划算法,求出这个矩阵连乘积问题的最优计算顺序。
  9. 实现要求:随机生成n个合法的可连乘的矩阵,以完全加括号的方式输出其最优计算顺序。

LIS Question

01.jpg-311.8kB

  1. // test5.1.cpp :
  2. // 1.最长递增子序列问题
  3. //【问题描述】
  4. //给定一个整数数组,设计一个动态规划算法求出该数组中的最长递增子序列。
  5. //
  6. #include "stdafx.h"
  7. #include <iostream>
  8. using namespace std;
  9. // 输出LIS 序列
  10. void outputLIS(int * arr, int index, int lis, int *L)
  11. {
  12. //终止条件
  13. if (lis == 0 || index < 0)
  14. return;
  15. //找到第一个L[index]==lis
  16. while (L[index]!=lis && index>0)
  17. index--;
  18. //反序输出
  19. if (index >= 0 && L[index]==lis)
  20. {
  21. outputLIS(arr, index - 1, lis - 1, L);
  22. cout << arr[index] << ",";
  23. }
  24. }
  25. int LIS(int *a, int n)
  26. {
  27. //定义一个存取结果的数组
  28. int *L = new int[n];
  29. //填写次序 0 to n-1
  30. for (int j = 0; j < n;j++)
  31. {
  32. L[j] = 1;//BaseCase
  33. //find max L[i]
  34. for (int i = 0; i < j;i++)
  35. {
  36. if (a[i]<a[j] && L[i]+1 > L[j])
  37. {
  38. L[j] = L[i] + 1;
  39. }
  40. }
  41. }
  42. //return the max of L[0~n-1]
  43. int max = L[0];
  44. for (int i = 0; i < n; i++)
  45. {
  46. //cout << L[i] << " ";
  47. if (L[i]>max)
  48. {
  49. max = L[i];
  50. }
  51. }
  52. //回溯输出
  53. cout << "LIS如下:";
  54. outputLIS(a, n,max, L);
  55. return max;
  56. }
  57. int main()
  58. {
  59. int a[] = { 5, 2, 8, 6, 3, 6, 9, 7, };
  60. int n = sizeof(a) / sizeof(int);
  61. cout<<endl<<"长度为:" << LIS(a, n) << endl;
  62. return 0;
  63. }
添加新批注
在作者公开此批注前,只有你和作者可见。
回复批注