-
Notifications
You must be signed in to change notification settings - Fork 0
/
624 - CD.cpp
88 lines (79 loc) · 1.54 KB
/
624 - CD.cpp
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
#include <iostream>
#include <algorithm>
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <vector>
#include <stack>
#include <map>
#define ll long long
using namespace std;
// vector ip trong ham main
vector<int> ip;
// value
int N;
int Max;
// vector trong ham backtrack
vector<int> solution;
vector< vector<int> > rs; // vector chua cac dap an
// vector tam de cho vao rs
vector<int> tmp;
void backtrack(int left, int tong){
if(left==ip.size() || tong >N ){
if(tong>N){ // do tong>N phai bo con so cuoi cung
int s=0;
for(int j=0;j<solution.size()-1;j++){ //j<solution.size()-1 ; khong lay so cuoi cung
s+=solution[j];
tmp.push_back(solution[j]);
}
if(Max<s) Max=s;
rs.push_back(tmp);
tmp.clear();
return;
}
int s=0;
for(int j=0;j<solution.size();j++){
s+=solution[j];
}
if(Max<s) Max=s;
rs.push_back(solution);
return;
}
for(int i=left;i<ip.size();i++){
solution.push_back(ip[i]);
backtrack(1+i,tong+ip[i]);
// xoa tai cho
solution.pop_back();
}
}
int main(){
// freopen("ip.txt","r",stdin);
// freopen("rs.txt","w",stdout);
while(cin >> N){
Max=0;
int n; cin >> n;
int a;
for(int i=0;i<n;i++){
cin >> a;
ip.push_back(a);
}
// chay de quy
backtrack(0,0);
// in output
for(int i=0;i<rs.size();i++){
int ss=0;
for(int j=0;j<rs[i].size();j++){
ss+=rs[i][j];
}
if(ss==Max){
for(int j=0;j<rs[i].size();j++)
cout << rs[i][j]<< " ";
break;
}
}
cout << "sum:" << Max << endl;
//reset
ip.clear();
rs.clear();
}
}