E - Knapsack 2
Problem Statement
There are NN items, numbered 1,2,…,N1,2,…,N. For each ii (1≤i≤N1≤i≤N), Item ii has a weight of wiwi and a value of vivi.
Taro has decided to choose some of the NN items and carry them home in a knapsack. The capacity of the knapsack is WW, which means that the sum of the weights of items taken must be at most WW.
Find the maximum possible sum of the values of items that Taro takes home.
Constraints
- All values in input are integers.
- 1≤N≤1001≤N≤100
- 1≤W≤1091≤W≤109
- 1≤wi≤W1≤wi≤W
- 1≤vi≤1031≤vi≤103
Input
Input is given from Standard Input in the following format:
NN WW w1w1 v1v1 w2w2 v2v2 :: wNwN vNvN
Output
Print the maximum possible sum of the values of items that Taro takes home.
Sample Input 1 Copy
3 8 3 30 4 50 5 60
Sample Output 1 Copy
90
Items 11 and 33 should be taken. Then, the sum of the weights is 3+5=83+5=8, and the sum of the values is 30+60=9030+60=90.
Sample Input 2 Copy
1 1000000000 1000000000 10
Sample Output 2 Copy
10
Sample Input 3 Copy
6 15 6 5 5 6 6 4 6 6 3 5 7 2
Sample Output 3 Copy
17
Items 2,42,4 and 55 should be taken. Then, the sum of the weights is 5+6+3=145+6+3=14, and the sum of the values is 6+6+5=176+6+5=17.
#include <iostream> #include <vector> #include <algorithm> #include <string> #include <set> #include <queue> #include <map> #include <sstream> #include <cstdio> #include <cstring> #include <numeric> #include <cmath> #include <iomanip> #include <deque> #include <bitset> #include <unordered_set> #include <unordered_map> #define ll long long #define PII pair<int, int> #define rep(i,a,b) for(int i=a;i<=b;i++) #define dec(i,a,b) for(int i=a;i>=b;i--) using namespace std; int dir[4][2] = { { 0,1 } ,{ 0,-1 },{ 1,0 },{ -1,0 } }; const long long INF = 0x7f7f7f7f7f7f7f7f; const int inf = 0x3f3f3f3f; const double pi = 3.14159265358979323846; const double eps = 1e-6; const int mod =1e9+7; const int N = 1e5+5; //if(x<0 || x>=r || y<0 || y>=c) inline ll read() { ll x = 0; bool f = true; char c = getchar(); while (c < '0' || c > '9') { if (c == '-') f = false; c = getchar(); } while (c >= '0' && c <= '9') x = (x << 1) + (x << 3) + (c ^ 48), c = getchar(); return f ? x : -x; } ll gcd(ll m, ll n) { return n == 0 ? m : gcd(n, m % n); } ll lcm(ll m, ll n) { return m * n / gcd(m, n); } bool prime(int x) { if (x < 2) return false; for (int i = 2; i * i <= x; ++i) { if (x % i == 0) return false; } return true; } ll qpow(ll m, ll k, ll mod) { ll res = 1, t = m; while (k) { if (k & 1) res = res * t % mod; t = t * t % mod; k >>= 1; } return res; } int main() { ll n,w; cin >> n >> w; vector<pair<ll, ll>> a(n + 1); vector<vector<ll>> dp(n + 1,vector<ll>(N)); rep(i, 1, n) { cin >> a[i].first>>a[i].second; } rep(i, 1, 1e5) { dp[0][i] = inf; } rep(i, 1, n) { rep(j, 1, 1e5) { if ( j >=a[i].second) dp[i][j] = min(dp[i - 1][j],dp[i - 1][j-a[i].second] + a[i].first); else dp[i][j] = dp[i - 1][j]; } } ll res = 0; dec(i,1e5,0) { if (dp[n][i] <= w) { res = i; break; } } cout << res << endl; return 0; }