You're not handling the batch costs correctly. You are not defining your dp-state correctly.
On a stylistic note, your code is poorly formatted. You seem to be unsure of where you want to put brackets and the number of spaces or tabs you want to use. In case it is useful to you, here is how I formatted your code. There is no right or wrong way to do this (though many disagree on this point), the key is to be consistent. Well formatted code is easy to read and debug.
#include <stdio.h>
int K[500][1010];
int max(int a, int b) {
return (a > b)? a : b;
}
int knapSack(int W, int wt[], int val[], int n, int m, int b[]) {
int i, w;
int flag[50]={0};
for (i = 0; i <= n*m; i++) {
for (w = 0; w <= W; w++) {
if (i==0 || w==0)
K[i][w] = 0;
else {
if(flag[(i-1)/m]==0) {
if (wt[i-1]+b[(i-1)/m] <= w) {
K[i][w] = max(val[i-1] + K[i][w-wt[i-1]-b[(i-1)/m]], K[i-1][w]);
if(K[i][w]!=K[i-1][w])
flag[(i-1)/m]=1;
}
else {
K[i][w] = K[i-1][w];
}
}
else {
if (wt[i-1]+b[(i-1)/m] <= w) {
K[i][w] = max(val[i-1] + K[i][w-wt[i-1]], K[i-1][w]);
}
else {
K[i][w] = K[i-1][w];
}
}
}
// printf("%ld ",K[i][w]);
}
}
// printf("\n");'}
return K[n*m][W];
}
int main(){
int t;
scanf("%d",&t);
int n,m,k,i,j;
int cost[2000],power[2000],batch[2000];
while(t--) {
scanf("%d %d %d",&n,&m,&k);
for(i=0;i<n;i++)
scanf("%d",&batch[i]);
for(i=0;i<n*m;i++)
scanf("%d",&cost[i]);
for(i=0;i<n*m;i++)
scanf("%d",&power[i]);
int p= knapSack(k,cost,power,n,m,batch);
printf("%d\n",p);
}
return 0;
}