Quiz 2-2eng

You might also like

Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 2

1.

Write an algorithm (using a Dynamic Programming) of finding the largest total cost of things that we
have to choose from the given things (with cost's c 1, c2 ,…, cn and with weights m1,m2,…,mn) and
put them in our bag if we can’t carry more than M kg. Write a short explanation of initial and main
recurrent formulas; (1 point)
T[0][0]=0;
for(j=1; j<=m; j++)
T[0][j]=0;
for(i=1; i<=n; i++)
T[i][0]=0;
for(i=0; i<=n; i++)
{
for(j=0; j<=m; j++)
{
if(M[i]<=j)
{
T[i][j]=max(T[i-1][j], T[i-1][j-M[i]]+C[i]);
}
Else
{
T[i][j]=T[i-1][j];
}
}
2. You have to choose things with largest total cost from the given four things with weights m 1=5 kg,
m2=2 kg, m3=4 kg, m4=7 kg and with costs c1=4, c2=7, c3=5, c4=8 if you can’t carry more than 15 kg.
Build the dynamic array with the proper size, fill it with the solutions of subtasks and find the
solution of the main task; (0.5 point)

M[1]=5; C[1]=4;
M[2]=2; C[2]=7;
M[3]=4; C[3]=5;
M[4]=7; C[4]=8;

i/j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0
1 0 0 0 0 0 4 4 4 4 4 4 4 4 4 4 4
2 0 0 7 7 7 7 7 11 11 11 11 11 11 11 11 11
3 0 0 7 7 7 7 12 12 12 12 12 16 16 16 16 16
4 0 0 7 7 7 7 12 12 12 15 15 16 16 20 20 20

3. Given n activities. It’ known the start and end times of each activities (s i and fi are start and end
times of ith activity). If any two activities are overlap (intersect each other) it’s possible to choose
only one from them. It’s allowed if the the end time of next activity is equal to the start time of
previous activity.
Write an algorithm of finding maximal number of compatible (not intersected) activities; (1 point)
n=length[s]
A={1}
j=1;
for(i=2;i<=n;i++)
if(si ≥ fi){
A=Ai}
j=i
}
return A
4. Given sequence of integer numbers: (1, 0, 3, 2, 5, 7, 4, 9, 15, 6, 8, 20, 10). You have to find maximal
increasing subsequence of the given sequence. Build the proper arrays B (dynmaic) and C (of
indices), fill them with solutions of subtasks and find the solution of a main task. (0.5 point)

A= (1 0 3 2 5 7 4 9 15 6 8 20 10 )
0 1 2 3 4 5 6 7 8 9 10 11 12

B= (1 1 2 2 3 4 3 5 6 4 5 7 6 )
0
1 2 3 4 5 6 7 8 9 10 11 12
C= (-1 -1 0 0 2 4 2 5 7 4 5 8 7 )
0 1 2 3 4 5 6 7 8 9 10 11 12

Answer is 1,3,5,7,9,15,20

You might also like