title: 俊文碎碎念date: 2020-11-27 12:09:33
tags: C++
categories: mumble

动态规划的方法求序列X,Y的最长公共子序列

  1. 以两个序列 XY 为例子: 设有二维数组 f[i][j] 表示 X i 位和 Y j 位之前的最长公共子序列的长度,则有:
  2. f[1][1] = same(1,1);
  3. f[i][j] = max{f[i-1][j -1] + same(i,j),f[i-1,j],f[i,j-1]}
  4. 其中,same(a,b)当 X 的第 a 位与 Y 的第 b 位完全相同时为“1”,否则为“0”。
  5. 最后f[lenX][lenY]即为最长公共子序列的值。
  6. 该算法的空间、时间复杂度均为O(n^2),经过优化后,空间复杂度可为O(n)。
  7. 4.代码实现:
  8. #include <cstdlib>   
  9. #include <iostream>   
  10. using namespace std;   
  11. #define N 105   
  12. int dp[N+1][N+1] ;   
  13. char str1[N] , str2[N];   
  14. int maxx(int a , int b)   
  15. {   
  16.   if(a > b)   
  17.     return a ;
  18.   return b ;   
  19. }   
  20. int LCSL(int len1 , int len2)   
  21. {   
  22.   int i , j ;   
  23.   int len = maxx(len1 , len2);   
  24.   for( i = 0 ; i <= len; i++ )   
  25.   {   
  26.     dp[i][0] = 0 ;dp[0][i] = 0 ;   
  27.   }   
  28.   for( i = 1 ; i<= len1 ; i++)   
  29.   {
  30.     for( j = 1 ; j <= len2 ; j++)   
  31.     {   
  32.       if(str1[i - 1] == str2[j - 1])   
  33.       {   
  34.         dp[i][j] = dp[i - 1][ j - 1] + 1 ;   
  35.       }   
  36.       else   
  37.       {   
  38.         dp[i][j] = maxx(dp[i - 1][ j ] , dp[i][j - 1]) ;   
  39.       }   
  40.     }
  41.   }  
  42.   return dp[len1][len2];   
  43. }   
  44. int main()   
  45. {   
  46.   while(cin >> str1 >> str2)   
  47.   {   
  48.     int len1 = strlen(str1) ;   
  49.     int len2 = strlen(str2) ;   
  50.     cout<<LCSL(len1 , len2)<<endl;   
  51.   }   
  52.   return 0;   
  53. }

sizeof求传入数组的长度问题

  1. 对传入数组求sizeof得到的只会是数组类型指针的大小,以下是解决办法
  2. #include <iostream>
  3. using namespace std;
  4. /*测试*/
  5. void test(int list[], int len)
  6. {
  7. cout << len;
  8. return;
  9. }
  10. int main()
  11. {
  12. int list[10] = { 1,4,3,5,7,9,2,6,8,0 };
  13. test(list, sizeof(list) / sizeof(int));
  14. return 0;
  15. }

memset 头文件

  1. #include <string> ×
  2. #include <string.h>

结构体struct和typedef后面接指针的含义

  1. typedef struct file{
  2. ...
  3. }*FileP,FileInfo;
  4. ] struct file 取个别名为FileInfo struct file * 取个别名为FileP

特殊字符的输出

  1. 想以符号输出如:\ " "这类符号时要用 \+符号的形式,会影响编程
  2. cout<<"\\\\"; 输出结果为 \\
  3. cout<<"\""; 输出结果为 "
  4. cout<<""""; 输出结果为 空
  5. cout<<"\"; 编译不过

二叉树的基本操作

链接

C++中push_back,push_front,insert的用法

链接

include使用方法简介

链接