I have a question where I have an array of elements with the following structure:
struct Band
{
int index;
int length;
int cost;
};
Now, I need to select a single or a combination of elements, where each of the elements having a unique index, i.e, none of the elements can have the same index. This combination of elements should have a sum of their lengths exactly equal to N, and if there are multiple such combinations, then I need to select the one with the minimum cost.
Any ideas? The current solution I have is not working, so I'm not sure if I should share it here or not. Thanks!
EDIT: Here's what I have right now. selected is the set of indices of elements selected, startI is starting index, ranageMax is the ending index (global). L is the required length and M is the maximum money that we have, so the cost must be lesser than it.
void knapsack(struct Band rubber[], int currLen, int cost, int startI, set<int> selected)
{
if(startI == rangeMax)
{
/*&root[startI].length = currLen;
root[startI].cost = cost;*/
cout << "\n";
return;
}
if(cost > M || currLen > L)
{
cout<< "\n";
return;
}
if(currLen == L)
{
//cout << "Candidate : " << cost << endl;
cout << "\n";
if(cost < minv)
minv = cost;
return;
}
for(int i=startI; i<rangeMax; ++i)
{
//knapsack(rubber, currLen, cost, startI+1, selected);
if(selected.find(rubber[i].index) == selected.end())
{
selected.insert(rubber[i].index);
cout << rubber[i].length << " ";
int tempCurrLen = currLen + rubber[i].length;
int tempCost = cost + rubber[i].cost;
/*root[i].length = currLen;
root[i].cost = cost;*/
knapsack(rubber, tempCurrLen, tempCost, i+1, selected);
selected.erase(rubber[i].index);
}
}
}