problem analysis:
First i thought of this as if s1, s2 and s3 are those three strings than if i find the lcs of s1 and s2 and again i call the same function for the lcs of (lcs of s1 and s2) and s3 than that is my answer after coding the commented down below part i found that it is not entirely true as we all know any two strings can have not single but many lcs so if i find a lcs for the first two strings and than run it with the third one that only means that specific lcs doesn't match with the third one but there may another lcs that matches entirely. so i had to change the whole structure . new one is similar to the lcs of two strings just it's 3D.
Here Goes the Code:
-
#include <bits/stdc++.h>
-
using namespace std;
-
string s1, s2, s3;
-
int l1, l2, l3;
-
int dp[50+1][50+1][50+1];
-
int lcs(){
-
memset(dp, 0, sizeof(dp));
-
for(int i = 1; i <= l1; i++){
-
for(int j = 1; j <=l2; j++){
-
for(int k= 1; k <= l3; k++){
-
if(s1[i-1] == s2[j-1] && s2[j-1] == s3[k-1])dp[i][j][k] = 1+ dp[i-1][j-1][k-1];
-
else dp[i][j][k] = max(max(dp[i][j][k-1], dp[i-1][j][k]), dp[i][j-1][k]);
-
}
-
}
-
}
-
return dp[l1][l2][l3];
-
}
-
int main(){
-
int ts;
-
scanf("%d", &ts);
-
for(int p = 1; p <=ts; p++){
-
cin>>s1>>s2>>s3;
-
l1 = s1.length();
-
l2 = s2.length();
-
l3 = s3.length();
-
printf("Case %d: %d\n", p, lcs());
-
}
-
return 0;
-
}
-
-
/*
-
int lcsa(){
-
memset(dp, 0, sizeof(dp));
-
for(int i = 1; i <= l1; i++){
-
for(int j = 1; j <=l2; j++){
-
if(s1[i-1] == s2[j-1])dp[i][j] = 1+ dp[i-1][j-1];
-
else dp[i][j] = max(dp[i][j-1], dp[i-1][j]);
-
}
-
}
-
-
for(int i = 0; i <= l1; i++){
-
for(int j = 0; j <= l2; j++){
-
printf("%d ", dp[i][j]);
-
}
-
printf("\n");
-
}
-
-
return dp[l1][l2];
-
}
-
string ans(){
-
int index = lcsa();
-
char lcs[index+1];
-
lcs[index] = '\0';
-
int i = l1, j = l2;
-
while (i > 0 && j > 0)
-
{
-
if (s1[i-1] == s2[j-1])
-
{
-
lcs[index-1] = s1[i-1]; // Put current character in result
-
i--; j--; index--; // reduce values of i, j and index
-
}
-
else if (dp[i-1][j] > dp[i][j-1]) i--;
-
else j--;
-
}
-
string ans(lcs);
-
return ans;
-
-
}
-
-
int main(){
-
int ts;
-
scanf("%d", &ts);
-
for(int p = 1; p <=ts; p++){
-
cin>>s1>>s2>>s3;
-
l1 = s1.length();
-
l2 = s2.length();
-
s1 = ans();
-
s2 = s3;
-
l1 = s1.length();
-
l2 = s2.length();
-
printf("Case %d: %d\n", p, lcsa());
-
}
-
return 0;
-
}
-
*/