summaryrefslogtreecommitdiffstats
path: root/01-algorithmic_toolbox/04-dynamic_programming/05-lcs3/lcs3.cpp
blob: 473830fc08621b8a96a9f7acfa917c7546e3db82 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
#include <iostream>
#include <vector>

using namespace std;

static inline int max(int a, int b, int c) {
    if (a > b)
        return (a > c ? a : c);
    return (b > c ? b : c);
}

static inline int max(int a, int b, int c, int d, int e, int f, int g) {
    int abc = max(a, b, c);
    int def = max(d, e, f);
    return max(abc, def, g);
}

int lcs3(vector<int> &a, vector<int> &b, vector<int> &c)
{
    vector<vector<vector<int> > > cost(a.size() + 1,
            vector<vector<int> >(b.size() + 1,
                vector<int>(c.size() + 1, 0)));

    int max_cost;;
    for (int k = 1; k <= c.size(); k++) {
        for (int j = 1; j <= b.size(); j++) {
            for (int i = 1; i <= a.size(); i++) {
                int c1 = cost[i - 1][j - 1][k - 1];     // -1 ; -1 ; -1
                int c2 = cost[i - 1][j - 1][k];         // -1 ; -1 ;  0
                int c3 = cost[i - 1][j][k - 1];         // -1 ;  0 ; -1

                int c4 = cost[i][j - 1][k - 1];         //  0 ; -1 ; -1
                int c5 = cost[i - 1][j][k];             // -1 ;  0 ;  0
                int c6 = cost[i][j - 1][k];             //  0 ; -1 ;  0
                int c7 = cost[i][j][k - 1];             //  0 ;  0 ; -1

                // (-1 ; -1 ; -1) + 1
                int c8_match = cost[i - 1][j - 1][k - 1] + 1;

                if (a[i - 1] == b[j - 1] && a[i - 1] == c[k - 1]) {
#if DEBUG
                    cout << "match " << a[i - 1] << " at (i, j, k) = " << i << "," << j << "," << k << endl;
#endif
                    max_cost = max(c8_match, c2, c3, c4, c5, c6, c7);
                } else {
                    max_cost = max(c1, c2, c3, c4, c5, c6, c7);
                }
                cost[i][j][k] = max_cost;
            }
        }
    }

#if DEBUG
    for (int k = 0; k <= c.size(); k++) {
        cout << "======== k = " << k << " =========" << endl;
        for (int j = 0; j <= b.size(); j++) {
            for (int i = 0; i <= a.size(); i++) {
                cout << cost[i][j][k] << " ";
            }
            cout << endl;
        }
    }
#endif

    return cost[a.size()][b.size()][c.size()];
}

int main() {
  size_t an;
  std::cin >> an;
  vector<int> a(an);
  for (size_t i = 0; i < an; i++) {
    std::cin >> a[i];
  }
  size_t bn;
  std::cin >> bn;
  vector<int> b(bn);
  for (size_t i = 0; i < bn; i++) {
    std::cin >> b[i];
  }
  size_t cn;
  std::cin >> cn;
  vector<int> c(cn);
  for (size_t i = 0; i < cn; i++) {
    std::cin >> c[i];
  }
  std::cout << lcs3(a, b, c) << std::endl;
}