Run
def knapSack(W, wt, val, n):
K = [[0 for x in range(W + 1)] for x in range(n + 1)]
for i in range(n + 1):
for w in range(W + 1):
if i == 0 or w == 0:
K[i][w] = 0
elif wt[i-1] <= w:
K[i][w] = max(val[i-1]
+ K[i-1][w-wt[i-1]],
K[i-1][w])
else:
K[i][w] = K[i-1][w]
res = K[n][W]
res1=res
x=0
w = W
for i in range(W+1):
if(K[n][i]==res):
x=i
break
print(x , res1)
b,n=map(int,input().split())
fun=[]
cost=[]
for i in range(n):
x,y=map(int,input().split())
fun.append(y)
cost.append(x)
(knapSack(b,cost,fun,n))
Run
import java.util.*;
class Solution
{
public static void main (String[]args)
{
Scanner sc = new Scanner (System.in);
while (true)
{
int budget = sc.nextInt ();
int n = sc.nextInt ();
if (budget == 0 && n == 0)
break;
int cost[] = new int[n + 1];
int fun[] = new int[n + 1];
int arr[][] = new int[n + 1][budget + 1];
for (int i = 0; i < n; i++)
{
cost[i] = sc.nextInt ();
fun[i] = sc.nextInt ();
}
for (int i = 0; i <= n; i++)
for (int j = 0; j <= budget; j++)
arr[i][j] = 0;
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= budget; j++)
if (cost[i - 1] <= j)
arr[i][j] =Math.max (fun[i - 1] + arr[i - 1][j - cost[i - 1]],arr[i - 1][j]);
else
arr[i][j] = arr[i - 1][j];
}
int c = 0;
for (int i = 0; i <= budget; i++)
{
if (arr[n][i] == arr[n][budget])
{
c = i;
break;
}
}
System.out.println (c + " " + arr[n][budget]);
}
}
}
Run
#include
using namespace std;
int main() {
int w, n;
x: cin >> w >> n;
if (w == 0 and n == 0)
goto r;
else {
int ct[n], val[n];
for (int i = 0; i < n; i++) {
cin >> ct[i] >> val[i];
}
int t[n + 1][w + 1];
for (int i = 0; i <= n; i++) {
for (int j = 0; j <= w; j++)
t[i][j] = 0;
}
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= w; j++) {
if (ct[i - 1] <= j)
t[i][j] = max(val[i - 1] + t[i - 1][j - ct[i - 1]], t[i - 1][j]);
else
t[i][j] = t[i - 1][j];
}
}
int cost = 0;
for (int i = 0; i <= w; i++) {
if (t[n][i] == t[n][w]) {
cost = i;
break;
}
}
cout << cost << " " << t[n][w] << endl;
goto x;
}
r: return 0;
}
Login/Signup to comment