Dynamic Programming: Data Structures and Algorithms
Dynamic Programming: Data Structures and Algorithms
Dynamic Programming: Data Structures and Algorithms
1|Page
Introduction
In this laboratory work we are going to solve problems by using one of the five
paradigms dynamic programming. In this report, we will try to explain how to solve
various problems by using dynamic approach to the given tasks.
Solution:
#include<iostream>
#include<vector>
#include<algorithm>
int *randomarr(int n)
{
int *a= new int[n];
for(int i=0; i<n;i++)
{
a[i]=rand()%50;
}
return a;
}
void lis(int *a, int n)
{
int *b = new int[n];
for (int i = 0; i < n; i++)
{
b[i]=1;
}
for (int i = 1; i < n; i++)
{
int j=0;
while(j!=i)
{
if(a[j]<a[i])
{
b[i]=max(b[j]+1,b[i]);
} j+
+;
}
}
vector<int> v;
int index=max_element(b,b+n)-b;
v.push_back(a[index]);
for (int i = index - 1; i >= 0 ; i--)
{
if(a[i]<a[index] && b[i]==b[index]-1)
{
v.push_back(a[i]);
index=i;
}
}
reverse(v.begin(),v.end());
cout<<*max_element(b,b+n)<<endl;
for (int i = 0; i < v.size(); i++)
{
cout<<v[i]<<" ";
}
cout<<endl;
}
int main()
{
int n;
cin>>n;
int *b;
b=randomarr(n);
for(int i=0; i<n ;i++)
{
cout<<b[i]<<" ";
}
cout<<endl;
lis(b,n);
system("pause");
return 0;
}
Task 2 – Coin collecting problem
• Let F(i,j) be the largest number of coins the robot can collect and bring to cell (i,j) in the ith
row and jth column.
• The recurrence:
Solution:
#include <bits/stdc++.h>
for(int i=1;i<n;i++)
for(int j=1;j<m;j++)
a[i][j]+=max(a[i-1][j],a[i][j-1]);
return a[n-1][m-1];
int main(){
int *arr[10];
for(int j=0;j<10;j++)
arr[i][j]=0;
for(int i=0;i<12;i++){
arr[x][y]) arr[x][y]=1;
else i--;
for(int i=0;i<10;i++){
for(int j=0;j<10;j++)
cout<<arr[i][j]<<' ';
cout<<endl;
cout<<collect_coins(arr,10,10)<<endl;
return 0;
for(int i=1;i<a.size();i++)
for(int j=1;j<b.size();j++)
if(a[i]==b[j])
arr[i][j]=arr[i-1][j-1];
else
arr[i][j]=min(arr[i-1][j-1],min(arr[i][j-1],arr[i-1][j]))+1;
return arr[a.size()-1][b.size()-1];
int main(){
string s,ss;
cin>>s>>ss;
cout<<edit_distance(s,ss)<<endl;
return 0;
max_so_far = 0
max_ending_here = 0
6|Page
Loop for each element of the array
max_ending_here = 0
return max_so_far
Simple idea of the Kadane’s algorithm is to look for all positive contiguous segments of the
array (max_ending_here is used for this). And keep track of maximum sum contiguous
segment among all positive segments (max_so_far is used for this). Each time we get a
positive sum compare it with max_so_far and update max_so_far if it is greater than
max_so_far
Solution:
#include <bits/stdc++.h>
for(int i=0;i<n;i++)
s=max(a[i],s+a[i]), maxx=max(maxx,s);
return maxx;
int main(){
int *arr,n;
for(int i=0;i<n;i++)
cout<<endl<<kadane(arr,n)<<endl;
delete[] arr;
return 0;
7|Page
}