forked from jahid-hridoy/Code_Templates
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUniqueString_LCS
More file actions
70 lines (56 loc) · 2.5 KB
/
UniqueString_LCS
File metadata and controls
70 lines (56 loc) · 2.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/*
The length of the shortest string that contains both the names as a subsequence.
Total number of unique shortest strings which contain the names as a subsequence.
*/
#include <bits/stdc++.h>
using namespace std;
int main()
{
ios::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
int testCases;
string name1, name2;
int shortestString[31][31];
long uniqueString[31][31];
cin >> testCases;
for (int testCase = 1; testCase <= testCases; testCase++)
{
cin >> name1 >> name2;
//Shift the characters of the name to right for ease of memoizing
name1.insert(0, "0");
name2.insert(0, "1");
//Prepare the matrices for memoization
for (int i = 0; i < 31; i++)
shortestString[0][i] = shortestString[i][0] = i, uniqueString[i][0] = uniqueString[0][i] = 1;
for (int i = 1; name1[i]; i++)
{
for (int j = 1; name2[j]; j++)
{
//Checking if we need to take the cumulative sum from upper-left block
if (name1[i] == name2[j])
{
//Adding 1 to cumulative sum from upper-left block
shortestString[i][j] = 1 + shortestString[i - 1][j - 1];
//No need to add a new branch of unique strings so taking cumulative sum from upper-left block
uniqueString[i][j] = uniqueString[i - 1][j - 1];
}
else
{
//Finding the minimum from left and upper block and adding 1 to the value of current block
shortestString[i][j] = 1 + min(shortestString[i][j - 1], shortestString[i - 1][j]);
//Checking if there are two unique strings of the same length
if (shortestString[i][j - 1] == shortestString[i - 1][j])
uniqueString[i][j] = uniqueString[i][j - 1] + uniqueString[i - 1][j];
//Checking if left block has the minimum value in shortestString matrix
else if (shortestString[i][j - 1] < shortestString[i - 1][j])
uniqueString[i][j] = uniqueString[i][j - 1];
else
uniqueString[i][j] = uniqueString[i - 1][j];
}
}
}
cout << "Case " << testCase << ": " << shortestString[name1.length() - 1][name2.length() - 1] << " " << uniqueString[name1.length() - 1][name2.length() - 1] << "\n";
}
return 0;
}