每种商品都跑一遍最小费用流就好了。
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <queue>
using namespace std;
#define ll long long
#define inf 0x3f3f3f3f
#define N 110
inline int read(){
int x=0,f=1;char ch=getchar();
while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();}
while(ch>='0'&&ch<='9') x=x*10+ch-'0',ch=getchar();
return x*f;
}
int n,m,K,h[N],num,T=100,dis[N],tot,cur[N],path[N],a[50][50],b[50][50];
bool inq[N];
struct edge{
int to,next,w,c;
}data[6000];
inline void add(int x,int y,int w,int c){
data[++num].to=y;data[num].next=h[x];h[x]=num;data[num].w=w;data[num].c=c;
data[++num].to=x;data[num].next=h[y];h[y]=num;data[num].w=0;data[num].c=-c;
}
inline bool spfa(){
deque<int>q;memset(dis,inf,sizeof(dis));memset(path,0,sizeof(path));
q.push_back(0);inq[0]=1;dis[0]=0;
while(!q.empty()){
int x=q.front();q.pop_front();inq[x]=0;
for(int i=h[x];i;i=data[i].next){
int y=data[i].to;if(!data[i].w) continue;
if(dis[x]+data[i].c<dis[y]){
dis[y]=dis[x]+data[i].c;path[y]=i;
if(!inq[y]){
if(!q.empty()&&dis[y]<dis[q.front()]) q.push_front(y);
else q.push_back(y);inq[y]=1;
}
}
}
}return path[T];
}
inline int solve(){
int ans=0,mxflow=0;
while(spfa()){
int low=inf,now=T;
while(path[now]) low=min(low,data[path[now]].w),now=data[path[now]^1].to;
mxflow+=low;ans+=low*dis[T];now=T;
while(path[now]) data[path[now]].w-=low,data[path[now]^1].w+=low,now=data[path[now]^1].to;
}if(mxflow!=tot) return -1;
return ans;
}
int main(){
// freopen("a.in","r",stdin);
while(1){
n=read();m=read();K=read();int ans=0;
if(!n&&!m&&!K) break;
for(int i=1;i<=n;++i)
for(int j=1;j<=K;++j) a[i][j]=read();
for(int i=1;i<=m;++i)
for(int j=1;j<=K;++j) b[i][j]=read();
for(int k=1;k<=K;++k){
memset(h,0,sizeof(h));num=1;tot=0;
for(int i=1;i<=n;++i)
for(int j=1;j<=m;++j) add(j+n,i,inf,read());
if(ans==-1) continue;
for(int i=1;i<=n;++i) add(i,T,a[i][k],0),tot+=a[i][k];
for(int j=1;j<=m;++j) add(0,j+n,b[j][k],0);
int res=solve();if(res==-1) ans=-1;else ans+=res;
}printf("%d\n",ans);
}return 0;
}