repl.it
@TaeHunKim/

algospot_packing

C++

No description

fork
loading
Files
  • main.cpp
main.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
#include<algorithm>
#include<cstdio>
#include<cstring>
#include<iostream>
#include<string>
#include<vector>
using namespace std;

int items, capacity;
int volume[100], need[100];
int cache[1001][100];
string name[100];

// 캐리어에 남은 용량이 capacity 일 때, item 이후의 물건들을 담아 얻을 수 있는 최대
// 절박도의 합을 반환한다
int pack(int capacity, int item) {
    if (item >= items)
        return 0;
    if (capacity <= 0)
        return 0;
    int &ret = cache[capacity][item];
    if (ret > -1)
        return ret;
    ret = pack(capacity, item+1);
    if(capacity >= volume[item])
        ret = max(ret, pack(capacity - volume[item], item+1) + need[item]);
	return ret;
}

// pack(capacity, item) 이 선택한 물건들의 목록을 picked 에 저장한다
void reconstruct(int capacity, int item, vector<string>& picked) {
    if (item >= items)
        return;
    if (capacity <= 0)
        return;
    if (pack(capacity, item) == pack(capacity, item+1))
        reconstruct(capacity, item+1, picked);
    else {
        picked.push_back(name[item]);
        reconstruct(capacity-volume[item], item+1, picked);
    }

}

int main() {
    int cases;
    cin >> cases;
    for(int cc = 0; cc < cases; ++cc) {
    	cin >> items >> capacity;
    	for(int i = 0; i < items; i++) {
    		cin >> name[i] >> volume[i] >> need[i];
    	}
    	memset(cache, -1, sizeof(cache));

        int needsum = pack(capacity, 0);
    	vector<string> picked;
    	reconstruct(capacity, 0, picked);
    	printf("%d %d\n", needsum, int(picked.size()));
    	for(int i = 0; i < picked.size(); ++i)
    		printf("%s\n", picked[i].c_str());
    }
}
Fetching token
?