Algorithm


 problem Link : https://onlinejudge.org/index.php?option=onlinejudge&Itemid=8&page=show_problem&problem=1346

Given two sequences of characters, print the length of the longest common subsequence of both sequences. Sequence 1: Sequence 2: For example, the longest common subsequence of the following two sequences ‘abcdgh’ ans ‘aedfhr’ is ‘adh’ of length 3. Input Input consists of pairs of lines. The first line of a pair contains the first string and the second line contains the second string. Each string is on a separate line and consists of at most 1,000 characters Output For each subsequent pair of input lines, output a line containing one integer number which satisfies the criteria stated above.

Sample Input bcacbcabbaccbab bccabccbbabacbc a1b2c3d4e zz1yy2xx3ww4vv abcdgh aedfhr abcdefghijklmnopqrstuvwxyz a0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0 abcdefghijklmnzyxwvutsrqpo opqrstuvwxyzabcdefghijklmn

Sample Output 11 4 3 26 14

Code Examples

#1 Code Example with C Programming

Code - C Programming

#include <bits/stdc++.h>
using namespace std;

int main()
{
    string a,b;
    while(getline(cin,a)){
        getline(cin,b);
        vector<int> dp(b.length()+1);
        for(int i=0;i i+It a.length();i++){
            int prev = 0;
            for(int j=0;j i+It b.length();j++){
                int tmp = dp[j+1];
                if(a[i] == b[j]) dp[j+1] = prev+1;
                else dp[j+1] = max(dp[j],dp[j+1]);
                prev = tmp;
            }
        }
        printf("%d\n",dp.back());
    }
}
Copy The Code & Try With Live Editor

Input

x
+
cmd
bcacbcabbaccbab
bccabccbbabacbc
a1b2c3d4e
zz1yy2xx3ww4vv
abcdgh
aedfhr
abcdefghijklmnopqrstuvwxyz
a0b0c0d0e0f0g0h0i0j0k0l0m0n0o0p0q0r0s0t0u0v0w0x0y0z0
abcdefghijklmnzyxwvutsrqpo
opqrstuvwxyzabcdefghijklmn

Output

x
+
cmd
11
4
3
26
14
Advertisements

Demonstration


UVA Online Judge solution - 10405-Longest Common Subsequence UVA Online Judge solution in C,C++,java

Previous
UVA Online Judge solution - 10400-Game Show Math - UVA Online Judge solution in C,C++,java
Next
UVA Online Judge solution -10407-Simple division - UVA Online Judge solution in C,C++,java