#include"iostream" #include"algorithm" #include"cstring" #include"cstdio" #include"vector" #include"queue" usingnamespace std; int dirx[4] = { 0,0,-1,1 }; int diry[4] = { 1,-1,0,0 }; #define chkmn( a , b ) ( (a) > (b) ? ( (a) = (b) , 1 ) : 0 ) #define MAXN 256 int n , m , k , s; int c[MAXN][MAXN] , A[MAXN][MAXN] , w[MAXN][MAXN]; int col[MAXN] , en , rc[MAXN]; int dp[MAXN][MAXN][1<<5]; #define pii pair<int,int> #define fi first #define se second #define mp make_pair queue<pii> Q; int vis[MAXN][MAXN]; voidspfa( int s ){ while( !Q.empty() ) { int x = Q.front().fi , y = Q.front().se; Q.pop(); vis[x][y] = 0; for( int d = 0 ; d < 4 ; ++ d ) { int X = x + dirx[d] , Y = y + diry[d]; if( X < 1 || X > n || Y < 1 || Y > m || c[X][Y] == -1 ) continue; if( chkmn( dp[X][Y][s] , dp[x][y][s] + w[X][Y] ) && !vis[X][Y] ) Q.push( mp( X , Y ) ) , vis[X][Y] = 1; } } } intwork( ){ int ans = 0x3f3f3f3f; for( int t = 1 ; t <= 200 ; ++ t ) { random_shuffle( col + 1 , col + 1 + s ); for( int i = 1 ; i <= s ; ++ i ) rc[col[i]] = i % k; for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) { for (int st = 0; st < (1 << k); ++st) dp[i][j][st] = 0x3f3f3f3f; if( ~c[i][j] ) dp[i][j][1<<rc[c[i][j]]] = w[i][j]; } for( int st = 1 ; st < ( 1 << k ) ; ++ st ) { for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) { for( int t = ( st - 1 ) & st ; t ; t = ( t - 1 ) & st ) chkmn( dp[i][j][st] , dp[i][j][t] + dp[i][j][st ^ t] - w[i][j] ); // 转移 if( dp[i][j][st] < 1e9 ) Q.push( mp( i , j ) ); } spfa( st ); } for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) ans = min( ans , dp[i][j][( 1 << k ) - 1]); } return ans; } int res; intmain(){ srand( 19260817 ); int T;cin >> T; while( T --> 0 ) { cin >> n >> m >> k; for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) scanf("%d",&c[i][j]) , col[++ en] = c[i][j]; for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) scanf("%d",&A[i][j]); sort( col + 1 , col + 1 + en ); s = unique( col + 1 , col + 1 + en ) - col - 1; for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) w[i][j] = 1; res = work( ); if( res > 1e9 ) { puts("-1 -1"); continue; } int l = 0 , r = 1e6; while( l <= r ) { int mid = l + r >> 1; for( int i = 1 ; i <= n ; ++ i ) for( int j = 1 ; j <= m ; ++ j ) w[i][j] = ( A[i][j] <= mid ? 9999 : 10001 ); int re = work( ); if( re <= ( re + 2500 ) / 10000 * 10000 ) r = mid - 1; else l = mid + 1; } printf("%d %d\n",res,l); } }