Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include<bits/stdc++.h>
- using namespace std;
- const int maxN = 1001;
- int grid[maxN][maxN];
- int solve(char s[],char t[],int i,int j,int n,int m) {
- if (i > n or j > m) {
- return 0;
- }
- if (grid[i][j] != -1) {
- return grid[i][j];
- }
- if (s[i] == t[j]) {
- return grid[i][j] = 1 + solve(s,t,i + 1,j + 1,n,m);
- } else {
- return grid[i][j] = max(solve(s,t,i + 1,j,n,m),solve(s,t,i,j + 1,n,m));
- }
- }
- int main () {
- ios::sync_with_stdio(false);
- cin.tie(nullptr);
- cout.tie(nullptr);
- int T = 1;
- //~ cin >> T;
- for (int test_case = 1; test_case <= T; ++test_case) {
- int n,m;
- cin >> n >> m;
- char s[n + 1],t[m + 1];
- for (int i = 1; i <= n; ++i) {
- cin >> s[i];
- }
- for (int i = 1; i <= m; ++i) {
- cin >> t[i];
- }
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= m; ++j) {
- grid[i][j] = -1;
- }
- }
- solve(s,t,1,1,n,m);
- for (int i = 1; i <= n; ++i) {
- for (int j = 1; j <= m; ++j) {
- cout << grid[i][j] << " ";
- }
- cout << "\n";
- }
- char lcs[grid[1][1] + 1];
- int i = 1,j = 1;
- int idx = 1;
- while (i <= n and j <= m) {
- if (s[i] == t[j]) {
- lcs[idx++] = s[i];
- ++i,++j;
- } else if (grid[i + 1][j] > grid[i][j + 1]) {
- ++i;
- } else{
- ++j;
- }
- }
- for (i = 1; i <= grid[1][1]; ++i) {
- cout << lcs[i];
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement