Solution for Knapsack 1 in C++


May 25, 2020 1.469919 seconds C++
#include <bits/stdc++.h>
using namespace std;

typedef long long LL; 
typedef pair<int, int> pii; 
typedef pair<LL, LL> pll; 
typedef pair<string, string> pss; 
typedef vector<int> vi; 
typedef vector<vi> vvi; 
typedef vector<pii> vii; 
typedef vector<LL> vl; 
typedef vector<vl> vvl;
typedef queue<int> qi;
typedef queue<char> qc;
typedef stack<int> si;
typedef stack<char> sc;
#define F first
#define S second
#define PB push_back


LL max(LL a, LL b){
	if(a > b){
		return a;
	}
	return b;
}

LL knap(LL n, LL c, LL w[], LL v[]){
	
	if(n == 0 || c == 0) return 0;
	
	if(w[n - 1] > c) return knap(n - 1, c, w, v);
	
	return max(knap(n - 1, c, w, v), v[n - 1] + knap(n - 1, c - w[n - 1], w, v));
}


int main(){
	ios::sync_with_stdio(0); cin.tie(0); cout.tie(0);
	LL n, c;
	cin >> n >> c;
	
	
	LL w[n], v[n];
	
	for(LL i = 0; i < n; i++){
		cin >> w[i] >> v[i];
	}
	
	cout << knap(n, c, w, v);
	return 0;
}

Editorial


No editorial for this problem. :(

Original Problem


You can view the original page for this problem on the DMOJ.