Need help of dynamic programming rod cutting? c++????? this is the verifier.cpp
ID: 3740436 • Letter: N
Question
Need help of dynamic programming rod cutting? c++?????
this is the verifier.cpp
#include <iostream>
using namespace std;
int main(int argc,char **argv) {
// Get the size of the sequence
int n = 1;
int* p;
cin >> n;
p = new int[n+1];
//read p;
p[0] = 0;
for(int i=1; i<=n; i++)
{
cin >> p[i];
}
// for(int i=1; i<=n; i++)
// cout << p[i]<< endl;
int total_length = 0;
int total_revenue = 0;
int student_claimed_revenue = 0;
int length = 0;
cin >> student_claimed_revenue;
do{
cin >> length;
if(length > 0)
{
total_length += length;
total_revenue += p[length];
}
}while(length >0);
//cout << total_length << endl;
//cout << total_revenue << endl;
int optimal_revenue;
cin >> optimal_revenue;
if (student_claimed_revenue != total_revenue || total_revenue != optimal_revenue)
cout << 0 << endl;
// Free allocated space
delete[] p;
return 1;
}
Explanation / Answer
#include<iostream>
#include<climits>
using namespace std;
int rodCutting(int n, int value[])
{
int total[n+1]; // array to store the total revenue
total[0]=0;
//total[i]=maximum attainable revenue of rod of size i
for(int i=1;i<=n;i++) // finding the result for rod of size i
{
total[i]=INT_MIN;
//try to cut the rod of length i into various values of j
//and select the one which gives the maximum value
for(int j=0;j<i;j++)
{
total[i]=max(total[i],value[j]+total[i-(j+1)]);
}
}
return total[n];
}
int main()
{
int n;
cin>>n;
cout << endl ;
int value[n];
for(int i=0;i<n;i++) //Enter the values of pieces of rod of all size
cin>>value[i];
cout<<rodCutting(n,value); //Maximum obtainable value by cutting up the rod in many pieces
cout<<endl;
return 0;
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.