Sunday, January 4, 2015

Techniques to solve Problem LightOJ 1013 - Love Calculator

Techniques of LightOJ 1013 - Love Calculator 

Category: This problem is mainly a Longest Common Subsequence Problem. 

Techniques: If you read carefully the problem statements then you should already know that this problem can be solved in two parts. 
In the first part what you need is to find the "The length of the shortest string that contains the names as subsequence" and in the second part what you need is that "Total number of unique shortest strings which contain the names as subsequence.". We are doing these in two parts too. 

First Part: Here, we are going to find the length of the shortest string that contains the names as subsequence. We can do this job in two ways as below.
  1. A way could be to find the longest common subsequence of the two given string and subtract it from the addition of the length of two given string.
    How does it work?
    We have to find the length of shortest string. So, We actually don't need to take a letter twice which is available in both the given string.
    Suppose, A=bac and B=mct. The the resultant shortest subsequence will be C=bamct.
    How? Answer: Since ba and c are not common at all so we have to take them all. now, next character c is common.Hence we can only take one. And at last t can be taken as the last character.
    I think you know how to find the lcs of two string. If don't then learn it.
  2. Another way two find the 1st part could be a modified version of
    longest common subsequence. In this process you don't need to subtract anything rather you do all the job in procedure lcs(). What you need here extra is that in the base case of recursive call, if any of the string got empty then you take the remaining letters in count. 

Second Part:  
The first part of this problem is relatively easy.  But the second part is a little bit thinking.
Since you know the length of the shortest string from first part, it is very helpful and necessary here. 
The function I have defined to do the work has three parameters. First is the present index of first string, second is the present index of second string and third is the number of characters we have taken till now.  
Case are:
If the two characters are same then proceed to the next characters by unique(i+1,j+1,num+1).
If two characters are not same then proceed by calling like follow:
ret=unique(i+1,j,num+1)+unique(i,j+1,num+1).

The base case is more important in my technique:

If any of the string got finished then what you will do?
My answer is, in common you add all the remaining letters from given strings with the num value from paremeter. If it is equal to length from first part then return 1(right approach:) ) else return 0(wrong approach :().


Comment if you have any Question.
 

4 comments: