-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathdp-5(bestsum).cpp
More file actions
95 lines (90 loc) · 1.7 KB
/
dp-5(bestsum).cpp
File metadata and controls
95 lines (90 loc) · 1.7 KB
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
#include<bits/stdc++.h>
#define ll long long int
using namespace std;
int target;
vector<vector<int> >v;
vector<int>x; ///this program works upto 10^5 within 1 sec
bool visit[10000];
vector<int>u;
bool bestsum(int n,int m,int a[])
{
if(n==target)
{
if(v[n][0]==-1)
{
v[n]=x;
}
else if(v[n].size()>x.size())
{
v[n]=x;
}
x.pop_back();
return true;
}
///memoization part
if(v[n][0]!=-1)
{
if(v[n].size()>x.size())
{
v[n]=x;
x.pop_back();
return true;
}
else if(x.size()>v[n].size()){
x.pop_back();
return true;;
}
else{
x.pop_back();
return true;;
}
}
for(int i=0; i<m; i++)
{
int r=n+a[i];
if(r<=target)
{
x.push_back(a[i]);
bestsum(r,m,a);
}
}
if(v[n][0]==-1)
{
v[n]=x;
}
else if(v[n].size()>x.size())
{
v[n]=x;
}
x.pop_back();
return false;
}
int main()
{
int n,m;
cin>>target>>m;
int a[m];
for(int i=0; i<m; i++)
{
cin>>a[i];
}
n=0;
for(int i=0; i<=target; i++)
{
vector<int>d;
d.push_back(-1);
v.push_back(d);
}
for(int i=0; i<=target; i++)
{
visit[i]=false;
}
sort(a, a + m, greater<int>());
bestsum(n,m,a);
for(int i=0; i<v[target].size(); i++)
{
cout<<v[target][i]<<" ";
}
cout<<endl;
return 0;
}