Saturday 21 March 2015

Write a program to find LCS (Longest common subsequence of two strings) using divide and conquer only.
First using divide and conquer only.
So , what is LCS of two strings 
Here is an eg of the same
first consider two strings a and b of lengths m and n respectively
LCS for Sequences “ABCDGH” and “AEDFHR” is “ADH” of length 3.
LCS for Sequences “AGGTAB” and “GXTXAYB” is “GTAB” of length 4.


Solution by Divide and Conquer

#include<stdio.h>
#include<string.h>
int lcs(char*, char*, int, int);
int smax(int, int);
int main()
{
char a[50],b[50];
int m,n;
printf("Enter the first sequence \n");
scanf("%s",a);
m=strlen(a);
printf("Enter the second one\n");
scanf("%s",b);
n=strlen(b);
printf("%d",lcs(a,b,m,n));
    return 0;
}
int lcs(char *a, char *b, int m , int n)
{
    if(m==0||n==0)
        return 0;
    else if(a[m-1]==b[n-1])
        return 1+lcs(a,b,m-1,n-1);
    else
        return smax(lcs(a,b,m-1,n),lcs(a,b,m,n-1));
}
int smax(int a,int b)
{
    if(a>b)
    return a;
    else
    return b;

}
Output:-







No comments:

Post a Comment