After reading the editorial for Knapsack Problem (KNPSK) I coded the following solution:-
#include <bits/stdc++.h>
using namespace std;
int main()
{
int n;
cin >> n;
vector <int> w1, w2;
int w, c;
for(int i=0; i<n; i++)
{
cin >> w;
if(w == 1)
{
cin >> c;
w1.push_back(c);
}
else
{
cin >> c;
w2.push_back(c);
}
}
sort(w1.begin(), w1.end());
sort(w2.begin(), w2.end());
vector <int> W1 = w1, W2 = w2;
int M = 2*w2.size() + w1.size();
int max_cost[M+1];
int cur = 0;
for(w=2; w<=M; w+=2)
{
int cost1 = 0, cost2 = 0;
if(w1.size() >= 1)
{
cost1 = w1.back();
}
int t = 1;
if(w1.size() >= 2)
{
cost1 = w1.back();
cost1 += w1[w1.size()-2];
t = 2;
}
if(w2.size() >= 1)
{
cost2 = w2.back();
}
if(cost1 > cost2)
{
cur += cost1;
if(t == 1)
{
w1.pop_back();
}
else
{
w1.pop_back();
w1.pop_back();
}
}
else
{
cur += cost2;
w2.pop_back();
}
max_cost[w] = cur;
}
max_cost[1] = W1.back();
W1.pop_back();
cur = max_cost[1];
for(w=3; w<=M; w+=2)
{
int cost1 = 0, cost2 = 0;
if(W1.size() >= 1)
{
cost1 = W1.back();
}
int t = 1;
if(W1.size() >= 2)
{
cost1 = W1.back();
cost1 += W1[W1.size()-2];
t = 2;
}
if(W2.size() >= 1)
{
cost2 = W2.back();
}
if(cost1 > cost2)
{
cur += cost1;
if(t == 1)
{
W1.pop_back();
}
else
{
W1.pop_back();
W1.pop_back();
}
}
else
{
cur += cost2;
W2.pop_back();
}
max_cost[w] = cur;
}
for(int i=1; i<M+1; i++)
cout << max_cost[i] << " ";
return 0;
}
The above code gives the correct output for the sample test case provided with the problem but gives WA straightaway on submission? I am unable to figure out the fault in the program logic? On which test cases does the above program fail? Can anyone please help me out so that I get an AC?