You are on page 1of 4

DAA

21BBS0050 LAB DA -3
R. ADIHTYA PAVAN

1.
#include <iostream>

#include <vector>

#include <algorithm>

using namespace std;

int longestCommonSubsequence(string s1, string s2, string& lcs) {

int m = s1.length();

int n = s2.length();

vector<vector<int>> dp(m + 1, vector<int>(n + 1, 0));

for (int i = 1; i <= m; i++) {

for (int j = 1; j <= n; j++) {

if (s1[i - 1] == s2[j - 1]) {

dp[i][j] = dp[i - 1][j - 1] + 1;

} else {

dp[i][j] = max(dp[i - 1][j], dp[i][j - 1]);

int length = dp[m][n];

lcs.resize(length);

int i = m, j = n;
while (i > 0 && j > 0) {

if (s1[i - 1] == s2[j - 1]) {

lcs[length - 1] = s1[i - 1];

i--;

j--;

length--;

} else if (dp[i - 1][j] > dp[i][j - 1]) {

i--;

} else {

j--;

return dp[m][n];

int main() {

string s1 = "ACCGGTCGATGCGGGAACATAAC";

string s2 = "GTCGTTACC";

string lcs;

int result = longestCommonSubsequence(s1, s2, lcs);

cout << "The length of the longest common subsequence is: " << result << endl;

cout << "The longest common subsequence is: " << lcs << endl;

return 0;

OUTPUT:
The overall time complexity O(m * n), indicating a linear relationship between the input sizes and the time
required to compute the longest common subsequence.

2)

#include <iostream>

#include <climits>

#include <vector>

using namespace std;

int matrixChainMultiplication(vector<int>& dimensions) {

int n = dimensions.size() - 1;

vector<vector<int>> dp(n, vector<int>(n, 0));

for (int len = 2; len <= n; len++) {

for (int i = 0; i < n - len + 1; i++) {

int j = i + len - 1;

dp[i][j] = INT_MAX;

for (int k = i; k < j; k++) {

int cost = dp[i][k] + dp[k + 1][j] + dimensions[i] * dimensions[k + 1] * dimensions[j + 1];


if (cost < dp[i][j])

dp[i][j] = cost;

return dp[0][n - 1];

int main() {

vector<int> dimensions = {4, 10, 3, 12, 20, 7};

int minimumCost = matrixChainMultiplication(dimensions);

cout << "Minimum cost of matrix chain multiplication: " << minimumCost << endl;

return 0;

Output:

The time complexity is O(n^3), indicating a cubic relationship between the number of matrices and the time
required to compute the minimum cost of matrix chain multiplication.

You might also like