here is my code
#include<bits/stdc++.h>
using namespace std;
#define ll long long int
#define INF 50000000000009999ll
using ld = long double;
using ull = unsigned long long;
int main()
{
int n,m,knapsack;
cin>>n>>m>>knapsack;
vector<int> weights(n+1),color(m+1);
for(int i=1;i<=n;i++)
cin>>weights[i];
for(int i=1;i<=n;i++)
cin>>color[i];
//storing weights of each color
vector<vector<int>> arr(m+1);
for(int i=1;i<=n;i++)
{
arr[color[i]].push_back(weights[i]);
}
//dp[i][j] means solution for i colors and j is knapsack or max value
int dp[m+1][knapsack+1];
memset(dp,-1,sizeof(dp));
//calculating value for case when we use color 1
for(int j=1;j<=knapsack;j++)
{
dp[1][j]=-1;
for(int w=0;w<arr[1].size();w++)
{
if(arr[1][w]<=j)
dp[1][j]=max(dp[1][j],arr[1][w]);
}
}
// calculating for rest of the colors
for(int i=2;i<=m;i++)
{
for(int j=1;j<=knapsack;j++)
{
dp[i][j]=-1;
if(i>j)
{
continue;
}
for(int w=0;w<arr[i].size();w++)
{
if(j> arr[i][w] && dp[i-1][j-arr[i][w]]>0)
dp[i][j]=max(dp[i][j],dp[i-1][j-arr[i][w]]+arr[i][w]);
}
}
}
if(dp[m][knapsack]!=-1)
cout<<knapsack-dp[m][knapsack];
else
cout<<"-1";
return 0;
}