HackerRank# The Longest Common Subsequence

原题地址

 

LCD,经典动归,O(n^2)复杂度

因为要输出子序列,所以啰嗦一些

 

 1 #include <cmath>

 2 #include <cstdio>

 3 #include <vector>

 4 #include <iostream>

 5 #include <algorithm>

 6 #include <cstring>

 7 using namespace std;

 8 

 9 #define MAX_LEN 128

10 

11 int n, m;

12 int a[MAX_LEN], b[MAX_LEN];

13 int lcd[MAX_LEN][MAX_LEN];

14 int start_index_a[MAX_LEN][MAX_LEN];

15 int start_index_b[MAX_LEN][MAX_LEN];

16 

17 int main() {

18     /* Enter your code here. Read input from STDIN. Print output to STDOUT */   

19     cin >> n >> m;

20     for (int i = 0; i < n; i++)

21         cin >> a[i];

22     for (int i = 0; i < m; i++)

23         cin >> b[i];

24     memset(lcd, 0, sizeof(lcd));

25     memset(start_index_a, 0, sizeof(start_index_a));

26     for (int j = 0; j < m; j++)

27         start_index_a[n][j] = start_index_b[n][j] = -1;

28     for (int i = 0; i < n; i++)

29         start_index_a[i][m] = start_index_b[i][m] = -1;

30     for (int i = n - 1; i >= 0; i--) {

31         for (int j = m - 1; j >= 0; j--) {

32             if (a[i] == b[j]) {

33                 lcd[i][j] = lcd[i + 1][j + 1] + 1;

34                 start_index_a[i][j] = i;

35                 start_index_b[i][j] = j;

36             } else if (lcd[i + 1][j] > lcd[i][j + 1]) {

37                 lcd[i][j] = lcd[i + 1][j];

38                 start_index_a[i][j] = start_index_a[i + 1][j];

39                 start_index_b[i][j] = start_index_b[i + 1][j];

40             } else {

41                 lcd[i][j] = lcd[i][j + 1];

42                 start_index_a[i][j] = start_index_a[i][j + 1];

43                 start_index_b[i][j] = start_index_b[i][j + 1];

44             }

45         }

46     }

47     

48     int i = start_index_a[0][0];

49     int j = start_index_b[0][0];

50     while (i >= 0 && j >= 0) {

51         cout << a[i] << " ";

52         int ii = start_index_a[i + 1][j + 1];

53         int jj = start_index_b[i + 1][j + 1];

54         i = ii;

55         j = jj;

56     }

57     cout << endl;

58     return 0;

59 }

 

你可能感兴趣的:(sequence)