-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMaxMoney.cpp
More file actions
147 lines (128 loc) · 3.09 KB
/
MaxMoney.cpp
File metadata and controls
147 lines (128 loc) · 3.09 KB
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
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
#include<bits/stdc++.h>
using namespace std;
bool isPowerOfTwo(int n){
if (n == 0)
{
return false;
}
return (ceil(log2(n)) == floor(log2(n)));
}
int max(int a, int b)
{
return (a > b) ? a : b;
}
int knapSack(int W, vector<int> &wt, vector<int> &val, int n)
{
int i, w;
vector<vector<int>> K(n + 1, vector<int>(W + 1));
// Build table K[][] in bottom up manner
for(i = 0; i <= n; i++)
{
for(w = 0; w <= W; w++)
{
if (i == 0 || w == 0)
K[i][w] = 0;
else if (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];
}
}
return K[n][W];
}
//Dp optimized space complexity
//S.C : O(W)//W is maxm weight capacity of knapsack
// int knapsack_DP_OpS(int wt[],int val[], int n, int mw){
int knapsack_DP_OpS(int mw, vector<int> &wt, vector<int> &val, int n){
int **DP = new int*[2];
for (int i = 0; i < 2; i++)
{
DP[i]= new int[mw + 1];
for (int j = 0; j < mw + 1; j++)
{
DP[i][j] = 0;
}
}
for (int i = 0; i < n; i++)
{
for (int j = 1; j <= mw; j++)
{
if (wt[i] > j)
{
DP[i%2][j] = DP[(i+1) %2][j];
}
else{
int a = val[i] + DP[(i+1) %2][j-wt[i]];
int b = DP[(i+1) % 2][j];
DP[i%2][j] = max(a,b);
}
}
}
return (n%2 == 0) ? DP[1][mw] : DP[0][mw];
}
//function
int maximizingMoney(int n, int m, vector<int> &b, vector<int> &c) {
// Write your code here.
vector<int> money(n);
for (int i = 0; i < n; i++)
{
int sq = floor(sqrt(b[i]));
if (isPowerOfTwo(b[i]))
{
money[i] = floor(log2(b[i]));
}
else{
money[i] = sq + 1;
}
}
// for (int i = 0; i < n; i++)
// {
// cout<<money[i]<<" ";
// }
int sum = knapsack_DP_OpS(m,c,money,n);
// typedef pair< float,pair<int,int>> pi;
// priority_queue<pi> pq;
// for (int i = 0; i < n; i++)
// {
// pair<int,int> temp;
// temp.first = money[i];
// temp.second = c[i];
// float m = money[i]/c[i];
// pq.push(make_pair(m,make_pair(money[i],c[i])));
// }
// int sum = 0;
// while (m != 0 && !pq.empty())
// {
// int diff = m - pq.top().second.second;
// if (diff> 0)
// {
// sum += pq.top().second.first;
// m = diff;
// // pq.pop();
// }
// pq.pop();
// }
return sum;
}
int main(){
int t;
cin>>t;
while (t--)
{
int n,m;
cin>>n>>m;
vector<int> b(n);
for (int i = 0; i < n; i++)
{
cin>>b[i];
}
vector<int> c(n);
for (int i = 0; i < n; i++)
{
cin>>c[i];
}
cout<<maximizingMoney(n,m,b,c)<<endl;
}
}