Problem link: https://onlinejudge.org/index.php?option=onlinejudge&page=show_problem&problem=565 Problem statement:

You have a long drive by car ahead. You have a tape recorder, but unfortunately your best music is on CDs. You need to have it on tapes so the problem to solve is you have a tape N minutes long. How to choose tracks from CD to get most out of tape space and have as short unused space as possible.Assumptions:•number of tracks on the CD does not exceed 20•no track is longer than N minutes•tracks do not repeat•length of each track is expressed as an integer number•N is also integer Program should find the set of tracks which fills the tape best and print it in the same sequence as the tracks are stored on the CD

Input:

Any number of lines. Each one contains value N, (after space) number of tracks and durations of the tracks. For example from first line in sample data:N=5, number of tracks=3, first track lasts for 1 minute, second one 3 minutes, next one 4 minutes.

Output:

Set of tracks (and durations) which are the correct solutions and string ‘sum:’ and sum of durationtimes.

Explanation:

Similar problem to the notorious backpack problem, so the solutions is definetly recursive.We just need to explore all the possible subsets and find the maximum sum of their elements.The recursive aproach gives a 2^n complexity because for each element there are 2 cases One in which the element is added and one in which is not.We do this while maintaining a string of the appended elements and return the closest sum and the string in the form of a pair.

My code:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
{#include <bits/stdc++.h>
using namespace std;


pair<int,string> rec(string str,int sum,int i,int goal,vector<int> v){
	
	if(sum>goal)return make_pair(-1,str);
	if(sum==goal||i==(int)v.size()){return make_pair(sum,str);}
	else{
		string s;
		int maxN;
		pair<int,string> p1;
		pair<int,string> p2;
		if((p1=rec(str,sum,i+1,goal,v)).first>=(p2=rec(str+" "+to_string(v[i]),sum+v[i],i+1,goal,v)).first){
			s=p1.second;
			maxN = p1.first;
			}
		else{
			s=p2.second;
			maxN = p2.first;
			}
		return make_pair(maxN,s);
		}
	}

int main(int argc, char **argv)
{
	int N;
	while(cin>>N){
		int k;
		cin>>k;
		vector<int> v(k);
		for(auto &a : v)cin>>a;
		pair<int,string>rabei = rec("",0,0,N,v);
		cout<<rabei.second<<" sum:"<<rabei.first<<endl;
		}
		return 0;
}}