#include<bits/stdc++.h>usingnamespace std;typedeflonglong ll;boolcmp(pair<ll,int> a, pair<ll,int> b){return a.first > b.first;}voidsolve(){srand(time(0));int n, m; cin >> n >> m;
vector<vector<ll>>a(n+10,vector<ll>(m+10));auto c = a, dp = a;
map<int, ll> cnt;for(int i =1; i <= n; i ++){for(int j =1; j <= m; j ++){
cin >> a[i][j];}}for(int i =1; i <= n; i ++){for(int j =1; j <= m; j ++){
cin >> c[i][j];
cnt[a[i][j]]+= c[i][j];}}
vector<pair<ll,int>> le;for(auto[a,b]: cnt){
le.push_back({b, a});}sort(le.begin(), le.end(), cmp);
function<ll(int)> fun =[&](int x)->ll{for(int i =1; i <= n; i ++){for(int j =1; j <= m; j ++){
dp[i][j]=max(dp[i-1][j], dp[i][j-1]);if(a[i][j]== x) dp[i][j]+= c[i][j];}}return dp[n][m];};
ll res =0;for(int i =0; i <min(40,(int)le.size()); i ++){
res =max(res,fun(le[i].second));}int times =0;while(times --){int x =rand()% le.size();
res =max(res,fun(le[x].second));}
cout << res << endl;}intmain(){
ios::sync_with_stdio(false); cin.tie(0);int t; cin >> t;while(t --)solve();return0;}