Problem:
E: Buttons
There is an $H \times W$ grid, with one button in each cell. Initially, all buttons are off. You will push them and turn them on.
Your task is to find a "good" timing of pressing the buttons. Let $t_{ij}$ be the timing to push the button of row $i$ and $j$ column . The timing is
said to be "good" if and only if the following conditions are satisfied.
$t_{ij}$ is an integer between $0$ and $10^9$ for all $i$ and $j$.
$t_{kl} + a_{ij} \leq t_{ij} \leq t_{kl} + b_{ij}$ for every cell $kl$ which is a horizontal or vertical neighbor of the cell $ij$, i.e., $|i − k| + |j − l| = 1$.
Write a program to output a "good" timing for the given $a$ and $b$. If there are several possible timings, you can output any of them. If
there is no "good" timing, you should output $-1$.
Input
The input consists of a single test case of the following format.
$H$ $W$
$a_{11}$ ... $a_{1W}$
:
$a_{H1}$ ... $a_{HW}$
$b_{11}$ ... $b_{1W}$
:
$b_{H1}$ ... $b_{HW}$
$H$ and $W$ represent the height and width of the given grid ($2 \leq H, W \leq 50$). $a_{ij}$ and $b_{ij}$represent the range of time differences for the
button of row $i$ and column $j$ ($-100,000 \leq a_{ij} \leq b_{ij} \leq 100,000$).
Output
If there is a "good" timing, output it in the following format.
$T_{11}$ ... $T_{1W}$
:
$T_{H1}$ ... $T_{HW}$
$T_{ij}$ is an integer representing the timing to push the button of row $i$ and column $j$. The timings should satisfy the conditions defined in
the problem statement. If there are multiple correct answers, you can print any of them.
If there is no "good" timing, you should output $-1$ instead.
Examples
Input 1
3 3
-2 1 -2
1 -2 1
-2 1 -2
-1 2 -1
2 -1 2
-1 2 -1
Output 1
0 1 0
1 0 2
0 2 0
Input 2
2 2
1 1
1 1
1 1
1 1
Output 2
-1

Submitted solutions:

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
using a2 = array<ll, 2>;
using a3 = array<ll, 3>;

bool chmin(auto& a, const auto& b) { return a > b ? a = b, 1 : 0; }
bool chmax(auto& a, const auto& b) { return a < b ? a = b, 1 : 0; }

const ll INF = 1e18;
ll mod = 998244353;

ifstream in;
ofstream out;

// 辺
struct Edge {
    int from;
    int to;
    int cost;
};

// ベルマンフォード法 (1.3 最短経路を再構築する)
// 負の閉路が存在する場合 true を返し, 負閉路の影響を受ける頂点は -INF
// にセットされる 頂点 T が負閉路の影響を受けない場合, 頂点 S からの最短経路を
// path に格納する dist は頂点数と同じサイズ, 全要素 INF で初期化しておく
bool BellmanFord(const vector<Edge>& eds, vector<ll>& dist, int S, int T,
                 vector<int>& path) {
    dist[S] = 0;

    vector<ll> p(ssize(dist), -1);

    bool changed = false;
    for (int i = 0; i < dist.size(); i++) {
        changed = false;
        // 各辺について
        for (const auto& ed : eds) {
            // (INF + cost) は INF なので処理しない
            if (dist[ed.from] == INF) continue;
            // to までの新しい距離
            const ll d = (dist[ed.from] + ed.cost);
            // d が現在の記録より小さければ更新
            if (d < dist[ed.to]) {
                dist[ed.to] = d;

                // 直前の頂点を記録
                p[ed.to] = ed.from;

                changed = true;
            }
        }

        // どの頂点も更新されなかったら終了
        if (!changed) {
            break;
        }
    }

    if (changed)  // 負閉路あり
    {
        // 頂点数分だけさらに繰り返し, 負閉路の影響を受ける頂点に -INF を伝播
        for (int i = 0; i < dist.size(); i++) {
            for (const auto& ed : eds) {
                if (dist[ed.from] == INF) continue;
                const ll d = (dist[ed.from] + ed.cost);
                // 負閉路の影響を受ける頂点を -INF に
                if (d < dist[ed.to]) dist[ed.to] = -INF;
            }
        }
    }
    if ((dist[T] != INF) &&
        (dist[T] != -INF))  // 頂点 T に到達不可または負閉路が影響する場合は最短経路無し
    {
        // 経路を再構築
        for (int i = T; i != -1; i = p[i]) path.push_back(i);
        reverse(path.begin(), path.end());
    }
    return changed;
}

int main(int argc, char** argv) {
    ios::sync_with_stdio(false);
    cin.tie(0);

    if (argc > 2) {
        in.open(argv[1]);
        cin.rdbuf(in.rdbuf());
        out.open(argv[2]);
        cout.rdbuf(out.rdbuf());
    }

    ll h, w;
    cin >> h >> w;
    vector<vector<ll>> a(h, vector<ll>(w, 0));
    vector<vector<ll>> b(h, vector<ll>(w, 0));

    for (auto& x : a)
        for (auto& y : x) cin >> y;
    for (auto& x : b)
        for (auto& y : x) cin >> y;

    vector<Edge> g(h * w);

    vector<a2> wasd = {
        {0, -1},
        {0, 1},
        {-1, 0},
        {1, 0},
    };

    vector<ll> dist(h * w, INF);

    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            for (auto [x, y] : wasd) {
                ll s = x + i, t = y + j;
                if (s < 0 || s >= h || t < 0 || t >= w)
                    continue;
                Edge e;
                e.from = i * w + j;
                e.to = s * w + t;
                e.cost = -a[i][j];
                g.push_back(e);

                swap(e.from, e.to);
                e.cost = b[i][j];
                g.push_back(e);
            }
        }
    }
    vector<int> p;
    auto res = BellmanFord(g, dist, 0, 1, p);
    if (res) {
        cout << -1 << endl;
        return 0;
    }
    for (int i = 0; i < h; i++) {
        for (int j = 0; j < w; j++) {
            cout << dist[i * w + j] + 5000000 << ' ';
        }
        cout << endl;
    }
    return 0;
}
accuracy: 1
time_ms: 110
memory_kb: 3968
final_rank: 15

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define vl vector<ll>
#define vvl vector<vl>
#define inf 1000000000000000000LL

vl dx={0,0,1,-1};
vl dy={1,-1,0,0};

struct path{
	ll node;
	ll cost;
};

int main(){
    ll h,w;
	cin>>h>>w;
	vvl a(h,vl(w));
	vvl b=a;
	rep(i,h)rep(j,w)cin>>a[i][j];
	rep(i,h)rep(j,w)cin>>b[i][j];

	vector<vector<path>> g(h*w);

	rep(i,h)rep(j,w){
		rep(d,4){
			ll nx=i+dx[d];
			ll ny=j+dy[d];
			if(nx<0||h<=nx||ny<0||w<=ny){
				continue;
			}

			ll ijtmp=i*w+j;
			ll nxytmp=nx*w+ny;
			g[ijtmp].push_back({nxytmp,-a[i][j]});
			g[nxytmp].push_back({ijtmp,b[i][j]});

			//cout<<ijtmp<<" "<<nxytmp<<" "<<-a[i][j]<<endl;
		}
	}

	vl dist(h*w,inf);

	dist[0]=500000000;
	bool ansok;
	rep(z,h*w*2){
		ansok=true;
		rep(i,h*w){
			rep(j,g[i].size()){
				ll next=g[i][j].node;
				ll cost=g[i][j].cost;
				if(dist[next]>dist[i]+cost){
					dist[next]=dist[i]+cost;
					ansok=false;
				}
			}
		}
	}


	if(!ansok){
		cout<<-1<<endl;
		return 0;
	}


	rep(i,h*w){
		cout<<dist[i]<<" ";
		if(i%w==w-1)cout<<endl;
	}
    return 0;
}
accuracy: 1
time_ms: 140
memory_kb: 3728
final_rank: 14

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define vl vector<ll>
#define vvl vector<vl>
#define inf 1000000000000000000LL

vl dx={0,0,1,-1};
vl dy={1,-1,0,0};

struct path{
	ll node;
	ll cost;
};

int main(){
    ll h,w;
	cin>>h>>w;
	vvl a(h,vl(w));
	vvl b=a;
	rep(i,h)rep(j,w)cin>>a[i][j];
	rep(i,h)rep(j,w)cin>>b[i][j];

	vector<vector<path>> g(h*w);

	rep(i,h)rep(j,w){
		rep(d,4){
			ll nx=i+dx[d];
			ll ny=j+dy[d];
			if(nx<0||h<=nx||ny<0||w<=ny){
				continue;
			}

			ll ijtmp=i*w+j;
			ll nxytmp=nx*w+ny;
			g[ijtmp].push_back({nxytmp,-a[i][j]});
			g[nxytmp].push_back({ijtmp,b[i][j]});

			//cout<<ijtmp<<" "<<nxytmp<<" "<<-a[i][j]<<endl;
		}
	}

	vl dist(h*w,inf);

	dist[0]=0;
	bool ansok;
	rep(z,h*w*2){
		ansok=true;
		rep(i,h*w){
			rep(j,g[i].size()){
				ll next=g[i][j].node;
				ll cost=g[i][j].cost;
				if(dist[next]>dist[i]+cost){
					dist[next]=dist[i]+cost;
					ansok=false;
				}
			}
		}
	}


	if(!ansok){
		cout<<-1<<endl;
		return 0;
	}


	rep(i,h*w){
		cout<<dist[i]<<" ";
		if(i%w==w-1)cout<<endl;
	}
    return 0;
}
accuracy: 0.5454545454545454
time_ms: 140
memory_kb: 3676
final_rank: 19

code_snippet: #include <bits/stdc++.h>
using namespace std;
using ll = long long;
#define rep(i, n) for (ll i = 0; i < n; ++i)
#define vl vector<ll>
#define vvl vector<vl>
#define inf 1000000000000000000LL

vl dx={0,0,1,-1};
vl dy={1,-1,0,0};

struct path{
	ll node;
	ll cost;
};

int main(){
    ll h,w;
	cin>>h>>w;
	vvl a(h,vl(w));
	vvl b=a;
	rep(i,h)rep(j,w)cin>>a[i][j];
	rep(i,h)rep(j,w)cin>>b[i][j];

	vector<vector<path>> g(h*w);

	rep(i,h)rep(j,w){
		rep(d,4){
			ll nx=i+dx[d];
			ll ny=j+dy[d];
			if(nx<0||h<=nx||ny<0||w<=ny){
				continue;
			}

			ll ijtmp=i*w+j;
			ll nxytmp=nx*w+ny;
			g[ijtmp].push_back({nxytmp,-a[i][j]});
			g[nxytmp].push_back({ijtmp,b[i][j]});

			//cout<<ijtmp<<" "<<nxytmp<<" "<<-a[i][j]<<endl;
		}
	}

	vl dist(h*w,inf);

	dist[0]=0;
	bool ansok;
	rep(z,h*w){
		ansok=true;
		rep(i,h*w){
			rep(j,g[i].size()){
				ll next=g[i][j].node;
				ll cost=g[i][j].cost;
				if(dist[next]>dist[i]+cost){
					dist[next]=dist[i]+cost;
					ansok=false;
				}
			}
		}
	}


	if(!ansok){
		cout<<-1<<endl;
		return 0;
	}


	rep(i,h*w){
		cout<<dist[i]<<" ";
		if(i%w==w-1)cout<<endl;
	}
    return 0;
}
accuracy: 0.5454545454545454
time_ms: 70
memory_kb: 3700
final_rank: 18

code_snippet: #include<bits/extc++.h>
#define rep(i,n) for(int i = 0; i<(n); i++)
#define all(a) begin(a),end(a)
using namespace std;
typedef long long ll;
typedef pair<int,int> P;
const int mod = 998244353;
const int inf = (1<<30);
const ll INF = (1ull<<62);
const int dx[8] = {1,0,-1,0,1,1,-1,-1};
const int dy[8] = {0,1,0,-1,1,-1,1,-1};
template<typename T1, typename T2>
inline bool chmax(T1 &a, T2 b){ return a < b && (a = b, true);}
template<typename T1, typename T2>
inline bool chmin(T1 &a, T2 b){ return a > b && (a = b, true);}

template<typename T = int>
struct Edge{
    int from,to;
    T cost;
    int idx;
    Edge() = default;
    Edge(int from, int to, T  cost = -1, int idx = -1): from(from), to(to), cost(cost),idx(idx){}
    operator int() const {return to;}
};

template<typename T = int>
struct Graph{
    vector<vector<Edge<T>>> g;
    int es;

    Graph() = default;

    explicit Graph(int n) : g(n), es(0) {}

    void add_d_edge(int from,int to, T cost = 1){
        g[from].emplace_back(from,to,cost,es++);
    }
};

template<typename T>
vector<T> bellman_ford(Graph<T>& edges, int n, int s, T MAX_T = numeric_limits<T>::max(), T MIN_T = numeric_limits<T>::min()){
    vector<T> dist(n,MAX_T);
    dist[s] = 0;
    for(int i = 0; i<n-1; i++){
        for(int j = 0; j<n; j++){
            for(auto& e : edges.g[j]){
                if(dist[e.from] == MAX_T) continue;
                dist[e.to] = min(dist[e.to],dist[e.from] + e.cost);
            }
        }
    }

    vector<bool> negative(n);
    for(int i = 0; i<n; i++){
        for(int j = 0; j<n; j++){
            for(auto& e : edges.g[j]){
                if(dist[e.from] == MAX_T) continue;
                if(dist[e.from] + e.cost < dist[e.to]){
                    dist[e.to] = dist[e.from] + e.cost;
                    negative[e.to] = true;
                }
                if(negative[e.from]){
                    negative[e.to] = true;
                }
            }
        }
    }
    for(int i = 0; i<n; i++){
        if(negative[i]) dist[i] = MIN_T;
    }
    return dist;
}

int main(){
    cin.tie(nullptr);
    ios_base::sync_with_stdio(false);
    cout.setf(ios_base::fixed);
    cout.precision(12);

    int h,w; cin>>h>>w;
    Graph<ll> G(h*w);
    vector<vector<ll>> a(h,vector<ll>(w));
    rep(i,h){
        rep(j,w){
            cin>>a[i][j];
        }
    }

    vector<vector<ll>> b(h,vector<ll>(w));
    rep(i,h){
        rep(j,w){
            cin>>b[i][j];
        }
    }

    for(int x = 0; x < h; x++){
        for(int y = 0; y<w; y++){
            rep(v,4){
                int nx = x + dx[v];
                int ny = y + dy[v];
                if(! (0 <= nx && nx < h && 0 <= ny && ny < w)) continue;
                G.add_d_edge(w*x + y , w*nx + ny , -a[x][y]);
                G.add_d_edge(w*nx + ny , w*x + y , b[x][y]);
            }
        }
    }

    vector<ll> ans = bellman_ford(G,h*w,0,INF,-INF);

    ll min_cost = inf;
    rep(i,h*w) chmin(min_cost, ans[i]);
    if(min_cost == -INF){
        cout<<-1<<endl;
        return 0;
    }
    rep(i,h){
        rep(j,w){
            cout<<ans[i*w + j] - min_cost;
            if(j != w-1) cout<<" ";
        }
        cout<<endl;
    }

}
accuracy: 1
time_ms: 130
memory_kb: 3876
final_rank: 16

code_snippet: #include<bits/stdc++.h>
// #include<atcoder/all>
// #include<boost/multiprecision/cpp_int.hpp>

using namespace std;
// using namespace atcoder;
// using bint = boost::multiprecision::cpp_int;
using ll = long long;
using ull = unsigned long long;
using ld = long double;
using pii = pair<int,int>;
using pll = pair<ll,ll>;
using vi = vector<ll>;
using vvi = vector<vi>;
using vvvi = vector<vvi>;
using ve = vector<vector<int>>;
using vb = vector<bool>;
using vvb = vector<vb>;
#define rep(i,s,n) for(ll i = (ll)s;i < (ll)n;i++)
#define rrep(i,l,r) for(ll i = r-1;i >= l;i--)
#define ALL(x) (x).begin(),(x).end()
#define sz(c) ((ll)(c).size())
#define LB(A,x) (int)(lower_bound(A.begin(),A.end(),x)-A.begin())
#define UB(A,x) (int)(upper_bound(A.begin(),A.end(),x)-A.begin())
// #define MOD 1000000007
#define MOD 998244353
template<typename T>using min_priority_queue=priority_queue<T,vector<T>,greater<T>>;
template<typename T>ostream&operator<<(ostream&os,vector<T>&v){for(int i = 0;i < v.size();i++)os<<v[i]<<(i+1!=v.size()?" ":"");return os;}
template<typename T>istream&operator>>(istream&is,vector<T>&v){for(T&in:v)is>>in;return is;}
template<typename T1,typename T2>ostream&operator<<(ostream&os,pair<T1,T2>&p){os<<p.first<<" "<<p.second;return os;}
template<typename T1,typename T2>istream&operator>>(istream&is,pair<T1,T2>&p){is>>p.first>>p.second;return is;}
template<typename T> inline bool chmax(T &a,T b){if(a < b){a = b;return true;}return false;}
template<typename T> inline bool chmin(T &a,T b){if(a > b){a = b;return true;}return false;}
ld dist(ld x1,ld y1,ld x2, ld y2){return sqrtl((x1-x2)*(x1-x2)+(y1-y2)*(y1-y2));}

int dx[] = {-1,0,0,1};
int dy[] = {0,-1,1,0};

int main(){
  
  ios_base::sync_with_stdio(0), cin.tie(0);
  int h,w;cin >> h >> w;
  vvi a(h,vi(w));
  vvi b(h,vi(w));
  cin >> a >> b;
  vector<tuple<ll,ll,ll>> v;
  rep(i,0,h)rep(j,0,w)rep(k,0,4){
    int ni = i + dy[k],nj = j + dx[k];
    if(ni < 0 || ni >= h || nj < 0 || nj >= w)continue;
    v.emplace_back(i*w +j,ni*w +nj,-a[i][j]);
    v.emplace_back(ni*w +nj,i*w +j,b[i][j]);
  }
  rep(i,0,h*w)v.emplace_back(h*w,i,0);
  const ll inf = 1ll << 60;
  vi d(h*w + 1,inf);
  d[h*w] = 0;
  rep(_,0,h*w+1){
    bool is = false;
    rep(i,0,sz(v)){
      auto [fr,to,we] = v[i];
      if(chmin(d[to],d[fr] + we))is = true;
    }
    if(_ == h*w && is){
      cout << -1 << endl;
      return 0;
    }
  }
  ll mn = inf;
  rep(i,0,h*w)chmin(mn,d[i]);
  rep(i,0,h*w)d[i] -= mn;
  rep(i,0,h)rep(j,0,w)cout << d[i*w + j] << " \n"[j+1 == w];
  

  return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 4096
final_rank: 17

code_snippet: #include<bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;i++)
using vll=vector<long long>;
using vvll=vector<vll>;
int main() {
    int H,W;
    cin>>H>>W;
    vvll A(H,vll(W,1e18));
    vvll B=A,D=A;
    rep(i,H)rep(j,W)cin>>A[i][j];
    rep(i,H)rep(j,W)cin>>B[i][j];
    bool ch;
    vll dx={1,0,-1,0},dy={0,1,0,-1};
    D[0][0]=1e8;
    rep(_,3000){
        ch=0;
        rep(h,H)rep(w,W)rep(d,4){
            int y=h+dy[d],x=w+dx[d];
            if(y<0||x<0||y>=H||x>=W)continue;
            if(D[y][x]>D[h][w]-A[h][w]){
                ch=1;
                D[y][x]=D[h][w]-A[h][w];
            }
            if(D[h][w]>D[y][x]+B[h][w]){
                ch=1;
                D[h][w]=D[y][x]+B[h][w];
            }
        }
    }
    if(ch)cout<<-1<<endl;
    else rep(h,H)rep(w,W)cout<<D[h][w]<<" \n"[w==W-1];
}
accuracy: 1
time_ms: 100
memory_kb: 3500
final_rank: 11

code_snippet: #include<bits/stdc++.h>
using namespace std;

using ll = long long;
#define rep(i,n) for(int i=0;i<n;i++)
using vll=vector<ll>;
using vvll=vector<vll>;
int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int H,W;
    cin>>H>>W;
    vvll A(H,vll(W)),B(H,vll(W));
    rep(i,H)rep(j,W)cin>>A[i][j];
    rep(i,H)rep(j,W)cin>>B[i][j];
    bool ch;
    vector<int> dx={1,0,-1,0},dy={0,1,0,-1};
    vvll D(H,vll(W,1e18));
    D[0][0]=1e8;
    rep(_,H*W+10){
        ch=0;
        rep(h,H)rep(w,W)rep(d,4){
            int y=h+dy[d],x=w+dx[d];
            if(y<0||x<0||y>=H||x>=W)continue;
            if(D[y][x]>D[h][w]-A[h][w]){
                ch=1;
                D[y][x]=D[h][w]-A[h][w];
            }
            if(D[h][w]>D[y][x]+B[h][w]){
                ch=1;
                D[h][w]=D[y][x]+B[h][w];
            }
        }
        if(!ch)break;
    }
    if(ch)cout<<-1<<endl;
    else rep(h,H)rep(w,W)cout<<D[h][w]<<" \n"[w==W-1];
}
accuracy: 1
time_ms: 70
memory_kb: 3480
final_rank: 4

code_snippet: #include<bits/stdc++.h>
using namespace std;

using ll = long long;
#define rep(i,n) for(int i=0;i<n;i++)
#define rep2(i,s,t) for(int i=s;i<t;i++)

using vll=vector<ll>;
using vvll=vector<vll>;

int main() {

    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    int H,W;
    cin>>H>>W;
    vvll A(H,vll(W)),B(H,vll(W));
    rep(i,H)rep(j,W)cin>>A[i][j];
    rep(i,H)rep(j,W)cin>>B[i][j];

    bool ch;
    vector<int> dx={1,0,-1,0},dy={0,1,0,-1};
    vvll D(H,vll(W,1e18));
    D[0][0]=1e8;
    rep(_,H*W+10){
        ch=0;
        rep(h,H)rep(w,W){
            rep(d,4){
                int y=h+dy[d];
                int x=w+dx[d];
                if(y<0||x<0||y>=H||x>=W)continue;
                if(D[y][x]>D[h][w]-A[h][w]){
                    ch=1;
                    D[y][x]=D[h][w]-A[h][w];
                }
                if(D[h][w]>D[y][x]+B[h][w]){
                    ch=1;
                    D[h][w]=D[y][x]+B[h][w];
                }
            }
        }
        if(!ch)break;

        // rep(h,H)rep(w,W)cout<<D[h][w]<<" \n"[w==W-1];
        // cout<<endl;
    }
    if(ch){
        cout<<-1<<endl;
    }
    else{
        rep(h,H)rep(w,W)cout<<D[h][w]<<" \n"[w==W-1];
    }

}
accuracy: 1
time_ms: 80
memory_kb: 3480
final_rank: 6

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, a, b) for (int i = (int)(a); i < (int)(b); i++)
#define rrep(i, a, b) for (int i = (int)(b)-1; i >= (int)(a); i--)
#define ALL(v) (v).begin(), (v).end()
#define UNIQUE(v) sort(ALL(v)), (v).erase(unique(ALL(v)), (v).end())
#define SZ(v) (int)v.size()
#define MIN(v) *min_element(ALL(v))
#define MAX(v) *max_element(ALL(v))
#define LB(v, x) int(lower_bound(ALL(v), (x)) - (v).begin())
#define UB(v, x) int(upper_bound(ALL(v), (x)) - (v).begin())

using uint = unsigned int;
using ll = long long int;
using ull = unsigned long long;
using i128 = __int128_t;
using u128 = __uint128_t;
const int inf = 0x3fffffff;
const ll INF = 0x1fffffffffffffff;

template <typename T> inline bool chmax(T &a, T b) {
    if (a < b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T> inline bool chmin(T &a, T b) {
    if (a > b) {
        a = b;
        return 1;
    }
    return 0;
}
template <typename T, typename U> T ceil(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? (x + y - 1) / y : x / y);
}
template <typename T, typename U> T floor(T x, U y) {
    assert(y != 0);
    if (y < 0)
        x = -x, y = -y;
    return (x > 0 ? x / y : (x - y + 1) / y);
}
template <typename T> int popcnt(T x) {
    return __builtin_popcountll(x);
}
template <typename T> int topbit(T x) {
    return (x == 0 ? -1 : 63 - __builtin_clzll(x));
}
template <typename T> int lowbit(T x) {
    return (x == 0 ? -1 : __builtin_ctzll(x));
}

template <class T, class U>
ostream &operator<<(ostream &os, const pair<T, U> &p) {
    os << "P(" << p.first << ", " << p.second << ")";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const vector<T> &vec) {
    os << "{";
    for (int i = 0; i < vec.size(); i++) {
        os << vec[i] << (i + 1 == vec.size() ? "" : ", ");
    }
    os << "}";
    return os;
}
template <typename T, typename U>
ostream &operator<<(ostream &os, const map<T, U> &map_var) {
    os << "{";
    for (auto itr = map_var.begin(); itr != map_var.end(); itr++) {
        os << "(" << itr->first << ", " << itr->second << ")";
        itr++;
        if (itr != map_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
template <typename T> ostream &operator<<(ostream &os, const set<T> &set_var) {
    os << "{";
    for (auto itr = set_var.begin(); itr != set_var.end(); itr++) {
        os << *itr;
        ++itr;
        if (itr != set_var.end())
            os << ", ";
        itr--;
    }
    os << "}";
    return os;
}
#ifdef LOCAL
#define show(...) _show(0, #__VA_ARGS__, __VA_ARGS__)
#else
#define show(...) true
#endif
template <typename T> void _show(int i, T name) {
    cerr << '\n';
}
template <typename T1, typename T2, typename... T3>
void _show(int i, const T1 &a, const T2 &b, const T3 &...c) {
    for (; a[i] != ',' && a[i] != '\0'; i++)
        cerr << a[i];
    cerr << ":" << b << " ";
    _show(i + 1, a, c...);
}

/**
 * @brief template
 */

int main() {
    int dx[4] = {1,0,-1,0}, dy[4] = {0,1,0,-1};
    int N, M;
    cin >> N >> M;
    auto encode = [&](int a, int b) -> int {
        return a*M+b;
    };
    vector<vector<int>> A(N,vector<int>(M)), B(N,vector<int>(M));
    rep(i,0,N) rep(j,0,M) cin >> A[i][j];
    rep(i,0,N) rep(j,0,M) cin >> B[i][j];
    int K = N * M;
    vector<vector<pair<int,int>>> G(K);
    rep(i,0,N) {
        rep(j,0,M) {
            rep(k,0,4) {
                int ni = i + dx[k], nj = j + dy[k];
                if (ni < 0 || N <= ni || nj < 0 || M <= nj) continue;
                int S = encode(i,j), T = encode(ni,nj);
                G[S].push_back({T,-A[i][j]});
                G[T].push_back({S,B[i][j]});
            }
        }
    }
    vector<int> DP(K,inf);
    DP[0] = 0;
    rep(_,0,K) {
        bool check = false;
        rep(i,0,K) {
            for (pair<int,int> P : G[i]) {
                if (chmin(DP[P.first], DP[i]+P.second)) check = true;
            }
        }
        if (_ == K-1 && check) {
            cout << -1 << endl;
            return 0;
        }
    }
    int MIN = inf;
    rep(i,0,K) chmin(MIN, DP[i]);
    rep(i,0,K) DP[i] -= MIN;
    rep(i,0,N) {
        rep(j,0,M) {
            cout << DP[encode(i,j)] << (j==M-1 ? '\n' : ' ');
        }
    }
}
accuracy: 1
time_ms: 60
memory_kb: 3536
final_rank: 3

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int main() {
    int H = in(), W = in();
    vector<vector<int>> A = in(H, W), B = in(H, W);

    const int INF = 1e9;
    vector D(H, vector(W, INF));
    D[0][0] = 0;
    bool neg = false;
    for(int t : rep(H * W)) {
        for(int i : rep(H)) for(int j : rep(W)) {
            for(auto [di, dj] : dir4) {
                int ni = i + di, nj = j + dj;
                if(0 <= ni and ni < H and 0 <= nj and nj < W) {
                    if(chmin(D[ni][nj], D[i][j] - A[i][j])) {
                        if(t == H * W - 1) neg = true;
                    }
                    if(chmin(D[i][j], D[ni][nj] + B[i][j])) {
                        if(t == H * W - 1) neg = true;
                    }
                }
            }
        }
    }

    if(neg) {
        print(-1);
    } else {
        int Min = 1e9;
        for(int i : rep(H)) for(int j : rep(W)) chmin(Min, D[i][j]);
        for(int i : rep(H)) for(int j : rep(W)) D[i][j] -= Min;
        for(int i : rep(H)) print(D[i]);
    }
}
accuracy: 1
time_ms: 80
memory_kb: 3496
final_rank: 7

code_snippet: #line 2 "cp-library/src/cp-template.hpp"
#include <bits/stdc++.h>
using namespace std;
using ll = long long;
using ld = long double;
using uint = unsigned int;
using ull  = unsigned long long;
using i32 = int;
using u32 = unsigned int;
using i64 = long long;
using u64 = unsigned long long;
using i128 = __int128_t;
template < class T > bool chmin(T& a, T b) { if(a > b) { a = b; return true; } return false; }
template < class T > bool chmax(T& a, T b) { if(a < b) { a = b; return true; } return false; }
template < class T, class U > T ceil (T x, U y) { return (x > 0 ? (x + y - 1) / y :           x / y); }
template < class T, class U > T floor(T x, U y) { return (x > 0 ?           x / y : (x - y + 1) / y); }
int popcnt(i32 x) { return __builtin_popcount(x); }
int popcnt(u32 x) { return __builtin_popcount(x); }
int popcnt(i64 x) { return __builtin_popcountll(x); }
int popcnt(u64 x) { return __builtin_popcountll(x); }

#line 2 "cp-library/src/utility/rep_itr.hpp"
template < class T > struct itr_rep {
    T i, d;
    constexpr itr_rep(const T i) noexcept : i(i), d(1) {}
    constexpr itr_rep(const T i, const T d) noexcept : i(i), d(d) {}
    void operator++() noexcept { i += d; }
    constexpr int operator*() const noexcept { return i; }
    constexpr bool operator!=(const itr_rep x) const noexcept { return d > 0 ? i < x.i : i > x.i; }
};

template < class T > struct rep {
    const itr_rep< T > s, t;
    constexpr rep(const T t) noexcept : s(0), t(t) {}
    constexpr rep(const T s, const T t) noexcept : s(s), t(t) {}
    constexpr rep(const T s, const T t, const T d) noexcept : s(s, d), t(t, d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};

template < class T > struct revrep {
    const itr_rep < T > s, t;
    constexpr revrep(const T t) noexcept : s(t - 1, -1), t(-1, -1) {}
    constexpr revrep(const T s, const T t) noexcept : s(t - 1, -1), t(s - 1, -1) {}
    constexpr revrep(const T s, const T t, const T d) noexcept : s(t - 1, -d), t(s - 1, -d) {}
    constexpr auto begin() const noexcept { return s; }
    constexpr auto end  () const noexcept { return t; }
};
#line 3 "cp-library/src/utility/io.hpp"

/* 128bit integer */
istream& operator>>(istream& is, i128& x) {
    std::string s; is >> s;
    int pm = (s[0] == '-');
    x = 0;
    for(int i : rep(pm, int(s.size()))) x = x * 10 + (s[i] - '0');
    if(pm) x *= -1;
    return is;
}
ostream& operator<<(ostream& os, const i128& x) {
    if(x == 0) return os << '0';
    i128 y = x;
    if(y < 0) { os << '-'; y *= -1; }
    std::vector<int> ny;
    while(y > 0) { ny.push_back(y % 10); y /= 10; }
    for(int i : revrep(ny.size())) os << ny[i];
    return os;
}

template < class S, class T > istream& operator>>(istream& is,       std::pair< S, T >& x) { is >> x.first        >> x.second; return is; }
template < class S, class T > ostream& operator<<(ostream& os, const std::pair< S, T >& x) { os << x.first << " " << x.second; return os; }

namespace scanner {
    struct sca {
        template < class T > operator T() {
            T s; std::cin >> s; return s;
        }
    };
    struct vec {
        int n;
        vec(int n) : n(n) {}
        template < class T > operator std::vector< T >() {
            std::vector< T > v(n);
            for(T& x : v) std::cin >> x;
            return v;
        }
    };
    struct mat {
        int h, w;
        mat(int h, int w) : h(h), w(w) {}
        template < class T > operator std::vector< std::vector< T > >() {
            std::vector m(h, std::vector< T >(w));
            for(std::vector< T >& v : m) for(T& x : v) std::cin >> x;
            return m;
        }
    };
    struct speedup {
        speedup() {
            std::cin.tie(0);
            std::ios::sync_with_stdio(0);
        }
    } speedup_instance;
}
scanner::sca in() { return scanner::sca(); }
scanner::vec in(int n) { return scanner::vec(n); }
scanner::mat in(int h, int w) { return scanner::mat(h, w); }

namespace printer {
    void precision(int d) { std::cout << std::fixed << std::setprecision(d); }
    void flush() { std::cout.flush(); }
}

template < class T >
ostream& operator<<(ostream& os, const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) { os << a[i]; if(i != n - 1) os << ' '; }
    return os;
}

int print() { std::cout << '\n'; return 0; }
template < class head, class... tail > int print(head&& h, tail&&... t) {
    std::cout << h; if(sizeof...(tail)) std::cout << ' ';
    return print(std::forward<tail>(t)...);
}
template < class T > int print_n(const std::vector< T > a) {
    int n = a.size();
    for(int i : rep(n)) std::cout << a[i] << "\n";
    return 0;
}


#line 2 "cp-library/src/utility/key_val.hpp"

template < class K, class V >
struct key_val {
    K key; V val;
    key_val() {}
    key_val(K key, V val) : key(key), val(val) {}
    template < std::size_t Index >
    std::tuple_element_t< Index, key_val >& get() {
        if constexpr (Index == 0) return key;
        if constexpr (Index == 1) return val;
    }
};

namespace std {

template < class K, class V > struct tuple_size < key_val< K, V > > : integral_constant< size_t, 2 > {};
template < class K, class V > struct tuple_element < 0, key_val< K, V > > { using type = K; };
template < class K, class V > struct tuple_element < 1, key_val< K, V > > { using type = V; };

}
#line 2 "cp-library/src/utility/vec_op.hpp"
template < class T > key_val< int, T > max_of(const vector< T >& a) {
    int i = std::max_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class T > key_val< int, T > min_of(const vector< T >& a) {
    int i = std::min_element(a.begin(), a.end()) - a.begin();
    return {i, a[i]};
}
template < class S, class T > S sum_of(const vector< T >& a) {
    S sum = 0;
    for(const T x : a) sum += x;
    return sum;
}
template < class S, class T > vector< S > freq_of(const vector< T >& a, T L, T R) {
    vector< S > res(R - L, S(0));
    for(const T x : a) res[x - L] += 1;
    return res;
}
template < class S, class T > struct prefix_sum {
    vector< S > s;
    prefix_sum(const vector< T >& a) : s(a) {
        s.insert(s.begin(), S(0));
        for(int i : rep(a.size())) s[i + 1] += s[i];
    }
    // [L, R)
    S sum(int L, int R) { return s[R] - s[L]; }
};
#line 3 "cp-library/src/utility/heap.hpp"

template < class T > using heap_min = std::priority_queue< T, std::vector< T >, std::greater< T > >;
template < class T > using heap_max = std::priority_queue< T, std::vector< T >, std::less< T > >;

#line 27 "cp-library/src/cp-template.hpp"

#line 1 "cp-library/src/algorithm/bin_search.hpp"
template < class T, class F >
T bin_search(T ok, T ng, F f) {
    while(abs(ng - ok) > 1) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}

template < class T, class F >
T bin_search_real(T ok, T ng, F f, int step = 80) {
    while(step--) {
        T mid = (ok + ng) / 2;
        (f(mid) ? ok : ng) = mid;
    }
    return ok;
}
#line 2 "cp-library/src/algorithm/argsort.hpp"

template < class T > std::vector< int > argsort(const std::vector< T > &a) {
    std::vector< int > ids((int)a.size());
    std::iota(ids.begin(), ids.end(), 0);
    std::sort(ids.begin(), ids.end(), [&](int i, int j) {
        return a[i] < a[j] || (a[i] == a[j] && i < j);
    });
    return ids;
}
#line 1 "macro.hpp"
namespace macro {

using size_type = int;
template < class container > void  sort(container& a) { std::sort(std:: begin(a), std:: end(a)); }
template < class container > void rsort(container& a) { std::sort(std::rbegin(a), std::rend(a)); }
template < class container > void reverse(container& a) { std::reverse(std::begin(a), std::end(a)); }
template < class container > void unique(container& a) {
    std::sort(std::begin(a), std::end(a));
    a.erase(std::unique(std::begin(a), std::end(a)), std::end(a));
}
template < class container > container  sorted(const container& a) { container b = a;  sort(b); return std::move(b); }
template < class container > container rsorted(const container& a) { container b = a; rsort(b); return std::move(b); }
template < class container, class compare > void sort(container& a, const compare& cmp) { std::sort(std::begin(a), std::end(a), cmp); }
template < class container, class compare > container sorted(const container& a, const compare& cmp) { container b = a; sort(b, cmp); return std::move(b); }
template < class container, class value > size_type lower_bound(const container& a, const value& x) { return std::lower_bound(std::begin(a), std::end(a), x) - std::begin(a); }
template < class container, class value > size_type upper_bound(const container& a, const value& x) { return std::upper_bound(std::begin(a), std::end(a), x) - std::begin(a); }

const std::vector<std::pair<size_type, size_type>> dir4 = { {+1,  0}, {-1,  0}, { 0, +1}, { 0, -1} };
const std::vector<std::pair<size_type, size_type>> dir8 = { {-1, -1}, {-1,  0}, {-1, +1}, { 0, -1}, { 0, +1}, {+1, -1}, {+1,  0}, {+1, +1} };

#ifdef _DEBUG
#define debug(x) std::cout << "[" << __LINE__ << "] " << #x << ": " << x << std::endl
#else
#define debug(x)
#endif

template < class container > void concat(container& a, const container& b) {
    a.insert(std::end(a), std::begin(b), std::end(b));
}
std::vector<size_type> iota(const size_type n) {
    std::vector<size_type> I(n);
    std::iota(std::begin(I), std::end(I), 0);
    return I;
}
template < class container > std::vector<size_type> sort_idx(const container& a) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return a[i] < a[j] or (a[i] == a[j] and i < j); });
    return I;
}
template < class container, class compare > std::vector<size_type> sort_idx(const container& a, const compare& cmp) {
    const size_type n = a.size();
    std::vector<size_type> I = iota(n);
    std::sort(std::begin(I), std::end(I), [&](size_type i, size_type j) { return cmp(a[i], a[j]) or (a[i] == a[j] and i < j); });
    return std::move(I);
}

struct grid {
    using size_type = int;
    size_type H, W;
    grid(const size_type H, const size_type W) : H(H), W(W) {}
    bool contains(const size_type i, const size_type j) {
        return 0 <= i and i < H and 0 <= j and j < W;
    }
};

using f64 = long double;

template < class T > vector< T >& operator++(vector< T >& a) { for(T& x : a) x++; return a; }
template < class T > vector< T >& operator--(vector< T >& a) { for(T& x : a) x--; return a; }
template < class T > vector< T >  operator++(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x++; return res; }
template < class T > vector< T >  operator--(vector< T >& a, signed) { vector< T > res = a; for(T& x : a) x--; return res; }

} // namespace macro

using namespace macro;
#line 3 "A.cpp"

int main() {
    int H = in(), W = in();
    vector<vector<int>> A = in(H, W), B = in(H, W);

    const int INF = 1e9;
    vector D(H, vector(W, INF));
    D[0][0] = 0;
    bool neg = false;
    for(int t : rep(H * W)) {
        for(int i : rep(H)) for(int j : rep(W)) {
            for(auto [di, dj] : dir4) {
                int ni = i + di, nj = j + dj;
                if(0 <= ni and ni < H and 0 <= nj and nj < W) {
                    if(chmin(D[ni][nj], D[i][j] - A[i][j])) {
                        if(t == H * W - 1) neg = true;
                    }
                    if(chmin(D[i][j], D[ni][nj] + B[i][j])) {
                        if(t == H * W - 1) neg = true;
                    }
                }
            }
        }
    }

    if(neg) {
        print(-1);
    } else {
        int Min = 1e9;
        for(int i : rep(H)) for(int j : rep(W)) chmin(Min, D[i][j]);
        for(int i : rep(H)) for(int j : rep(W)) D[i][j] -= Min;
        for(int i : rep(H)) print(D[i]);
    }
}
accuracy: 1
time_ms: 80
memory_kb: 3472
final_rank: 5

code_snippet: #include <bits/stdc++.h>

using namespace std;

#define rep(i, l, r) for (int i = (l); i < r; ++i)
#define rrep(i, l, r) for (int i = (r - 1); i >= l; --i)
#define all(c) begin(c), end(c)

#ifdef LOCAL
#define debug(...) debug_impl(#__VA_ARGS__, __VA_ARGS__)
template <class H, class... Ts> void debug_impl(string s, H&& h, Ts &&... ts) {
  cerr << '(' << s << "): (" << forward<H>(h);
  ((cerr << ", " << forward<Ts>(ts)), ..., (cerr << ")\n"));
}
#else
#define debug(...) void(0)
#endif

template <class T> bool chmax(T& a, const T& b) {
  return b > a ? (a = b, true) : false;
}
template <class T> bool chmin(T& a, const T& b) {
  return b < a ? (a = b, true) : false;
}

template <class T> istream& operator>>(istream& in, vector<T>& v) {
  for (auto& e : v) in >> e;
  return in;
}
template <class ... Args> void read(Args &... args) {
  (cin >> ... >> args);
}
template <class T> ostream& operator<<(ostream& out, const vector<T>& v) {
  int n = v.size();
  rep(i, 0, n) {
    out << v[i];
    if (i + 1 != n) out << ' ';
  }
  return out;
}
template <class H, class ... Ts> void print(H&& h, Ts &&...ts) {
  cout << h, ((cout << " " << forward<Ts>(ts)), ..., (cout << "\n"));
}

struct io_setup_ {
  io_setup_() {
    ios::sync_with_stdio(false), cin.tie(nullptr);
    cout << fixed << setprecision(10);
    cerr << fixed << setprecision(10);
  }
} io_setup{};

constexpr int dx[4]{ 1, 0, -1, 0 };
constexpr int dy[4]{ 0, 1, 0, -1 };

bool in(int x, int l, int r) {
  return l <= x and x < r;
}

constexpr long long inf = numeric_limits<long long>::max() / 2;

int main() {
  int h, w;
  read(h, w);
  vector a(h, vector<long long>(w));
  vector b(h, vector<long long>(w));
  read(a, b);

  vector<vector<pair<int, long long>>> g(h * w);
  rep(i, 0, h) rep(j, 0, w) {
    rep(dr, 0, 4) {
      int ni = i + dx[dr];
      int nj = j + dy[dr];

      if (in(ni, 0, h) and in(nj, 0, w)) {
        int u = i * w + j;
        int v = ni * w + nj;
        g[u].emplace_back(v, -a[i][j]);
        g[v].emplace_back(u, b[i][j]);
      }
    }
  }

  vector<long long> dist(h * w, inf);
  dist[0] = 0;

  rep(loop, 0, h * w + 2) {
    rep(u, 0, h * w) {
      for (auto [v, w] : g[u]) {
        chmin(dist[v], dist[u] + w);
      }
    }
  }

  bool inf_loop = false;
  rep(loop, 0, h * w) {
    rep(u, 0, h * w) {
      for (auto [v, w] : g[u]) {
        inf_loop |= chmin(dist[v], dist[u] + w);
      }
    }
  }
  if (inf_loop) {
    print(-1);
    return 0;
  }

  long long min_val = *min_element(all(dist));
  for (auto& e : dist) e -= min_val;
  rep(i, 0, h) rep(j, 0, w) {
    cout << dist[i * w + j] << " \n"[j == w - 1];
  }
}
accuracy: 1
time_ms: 130
memory_kb: 3660
final_rank: 13

code_snippet: #include<cstdio>
#include<algorithm>
#include<queue>
#include<cmath>
#include<iostream>
using namespace std;

#define Maxn 2510
#define INF 2000000000

const int dx[] = {-1, 0, 1, 0};
const int dy[] = {0, -1, 0, 1};

int H, W, a[51][51], b[51][51], dis[Maxn];

int main()
{
    scanf("%d%d", &H, &W);
    for (int i=1; i<=H; i++)
        for (int j=1; j<=W; j++)
            scanf("%d", &a[i][j]);
    for (int i=1; i<=H; i++)
        for (int j=1; j<=W; j++)
            scanf("%d", &b[i][j]);

    for (int i=1; i<=H*W; i++) dis[i] = INF; dis[1] = 0;
    
    int q = 0; bool Release = false;
    while (q < H * W)
    {
        q++;
        Release = false;
        for (int i=1; i<=H; i++)
            for (int j=1; j<=W; j++)
                for (int k=0; k<4; k++)
                {
                    int i_ = i + dx[k], j_ = j + dy[k];
                    if ((1 <= i_) && (i_ <= H) && ((1 <= j_) && (j_ <= W)))
                    {
                        int x = (i - 1) * W + j, y = (i_ - 1) * W + j_;
                        if ((dis[x] != INF) && (dis[y] > dis[x] + min(-a[i][j], b[i_][j_])))
                        {
                            Release = true;
                            if (q == H * W) { puts("-1"); return 0; }
                            dis[y] = dis[x] + min(-a[i][j], b[i_][j_]);
                        }
                    }
                }
        if (!Release) break;
    }
    int Min = INF;
    for (int i=1; i<=H*W; i++) Min = min(Min, dis[i]);
    for (int i=1; i<=H; i++)
    {
        for (int j=1; j<=W; j++)
            printf("%d ", dis[(i - 1) * W + j] - Min);
        puts("");
    }
}
accuracy: 1
time_ms: 60
memory_kb: 3520
final_rank: 2

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;



#define MAX_N 2505
#define MAX_E 20005


struct Edge{
	void set(int arg_from,int arg_to,ll arg_dist){
		from = arg_from;
		to = arg_to;
		dist = arg_dist;
	}
	int from,to;
	ll dist;
};

int V;
int H,W;
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
ll min_dist[MAX_N];
ll A[55][55],B[55][55];
Edge edge[MAX_E];

bool rangeCheck(int row,int col){

	return row >= 0 && row <= H-1 && col >= 0 && col <= W-1;
}

int getIndex(int row,int col){

	return row*W + col;
}

int main(){

	scanf("%d %d",&H,&W);
	V = H*W;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&A[row][col]);
		}
	}
	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&B[row][col]);
		}
	}

	int num_E = 0;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			int now = getIndex(row,col);

			for(int i = 0; i < 4; i++){
				int adj_row = row+diff_row[i];
				int adj_col = col+diff_col[i];
				if(!rangeCheck(adj_row,adj_col))continue;

				int adj = getIndex(adj_row,adj_col);

				edge[num_E++].set(now,adj,-A[row][col]);
				edge[num_E++].set(adj,now,B[row][col]);
			}

		}
	}

	min_dist[0] = 0;
	for(int i = 1; i < V; i++){

		min_dist[i] = HUGE_NUM;
	}

	bool FLG = true,updated;
	Edge tmp_e;

	for(int i = 0; i < V; i++){
		updated = false;
		for(int k = 0; k < num_E; k++){
			tmp_e = edge[k];
			if(min_dist[tmp_e.from] != HUGE_NUM && min_dist[tmp_e.to] > min_dist[tmp_e.from] + tmp_e.dist){
				min_dist[tmp_e.to] = min_dist[tmp_e.from] + tmp_e.dist;

				updated = true;
				if(i == V-1){
					FLG = false;
					break;
				}
			}
		}
		if(!updated)break;
		if(!FLG)break;
	}

	if(!FLG){
		printf("-1\n");
		return 0;
	}

	ll mini = HUGE_NUM;
	for(ll i = 0; i < V; i++){

		mini = min(mini,min_dist[i]);
	}
	for(ll i = 0; i < V; i++){

		min_dist[i] += abs(mini);
		if(min_dist[i] > 1000000000){

			printf("-1\n");
			return 0;
		}
	}

	for(int i = 0; i < V; i++){
		if(i%W == 0){

			printf("%lld",min_dist[i]);
		}else{

			printf(" %lld",min_dist[i]);
		}
		if((i+1)%W == 0){

			printf("\n");
		}
	}

	return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 3448
final_rank: 8

code_snippet: #include <iostream>
#include <algorithm>
#include <vector>

using namespace std;
constexpr int INF = 1 << 30;

const vector<pair<int, int>> dxys{{-1, 0}, {1, 0}, {0, -1}, {0, 1}};

void solve() {
    int h, w;
    cin >> h >> w;

    auto xss = vector(h, vector(w, 0));
    auto yss = xss;
    for (auto& xs : xss) {
        for (auto& x : xs) cin >> x;
    }
    for (auto& ys : yss) {
        for (auto& y : ys) cin >> y;
    }

    auto dist = vector(h, vector(w, INF));
    dist[0][0] = 0;

    for (int q = 0; q <= h * w; ++q) {
        bool update = false;

        for (int x = 0; x < h; ++x) {
            for (int y = 0; y < w; ++y) {
                for (auto [dx, dy] : dxys) {
                    auto nx = x + dx, ny = y + dy;
                    if (nx < 0 || h <= nx ||
                        ny < 0 || w <= ny) continue;

                    // (x,y)->(nx,ny) -a_{x,y}
                    // (x,y)->(nx,ny) b_{nx,ny}
                    auto nd = dist[x][y] + min(-xss[x][y], yss[nx][ny]);
                    if (nd < dist[nx][ny]) {
                        update = true;
                        dist[nx][ny] = nd;
                    }
                }
            }
        }

        if (!update) break;

        if (update && q == h * w) {
            // 負閉路あり
            cout << "-1\n";
            return;
        }
    }

    int mi = INF;
    for (const auto& ds : dist) {
        mi = min(mi, *min_element(ds.begin(), ds.end()));
    }
    for (const auto& ds : dist) {
        for (auto d : ds) {
            cout << d - mi << " ";
        }
        cout << "\n";
    }
}

int main() {
    cin.tie(nullptr);
    ios::sync_with_stdio(false);

    solve();

    return 0;
}
accuracy: 1
time_ms: 30
memory_kb: 3472
final_rank: 1

code_snippet: #include <cmath>
#include <vector>
#include <iostream>
#include <iomanip>
#include <fstream>
#include <algorithm>
#include <set>
#include <queue>
#include <string>
#include <map>
#include <stack>
#include <climits>
#include <array>
#include <unordered_set>
#include <unordered_map>
#include <memory>
#include <functional>
#include <cfloat>
#include <numeric>
#include <random>
#include <sstream>
#include <bitset>
#include <complex>
#include <chrono>
#include <cassert>

std::vector<long long int> min_distance(const int size, const std::vector<std::tuple<int, int, int>> edges, const int start) {
	std::vector<long long int> result(size, LLONG_MAX >> 1);
	result[start] = 0;
	for (auto i = 0; i < size; ++i) {
		bool renew{ false };
		for (const auto [from, to, cost] : edges) {
			if (result[to] > result[from] + cost) {
				result[to] = result[from] + cost;
				renew = true;
			}
		}
		if (!renew) return result;
	}
	return {};
}
bool check(const std::vector<std::vector<long long int>>& result, const std::vector<std::vector<int>>& a, const std::vector<std::vector<int>>& b) {
	constexpr std::array<int, 4> diff{ 0, 1, 0, -1 };
	for (auto i = 0; i < result.size(); ++i) {
		for (auto j = 0; j < result[i].size(); ++j) {
			const auto tij = result[i][j];
			for (auto d = 0; d < 4; ++d) {
				const auto k = i + diff[d];
				const auto l = j + diff[(d + 1) & 3];
				if (k < 0 || result.size() <= k) continue;
				if (l < 0 || result[k].size() <= l) continue;
				const auto tkl = result[k][l];
				if (tij < tkl + a[i][j] || tkl + b[i][j] < tij) {
					return false;
				}
			}
		}
	}
	return true;
}
std::vector<std::vector<long long int>> solve(const int height, const int width, const std::vector<std::vector<int>> a, const std::vector<std::vector<int>> b) {
	constexpr std::array<int, 4> diff{ 0, 1, 0, -1 };
	std::vector<std::tuple<int, int, int>> edges;
	for (auto i = 0; i < height; ++i) {
		for (auto j = 0; j < width; ++j) {
			const auto ij = i * width + j;
			edges.emplace_back(height * width, ij, 1000000000);
			edges.emplace_back(ij, height * width, 0);
			for (auto d = 0; d < 4; ++d) {
				const auto k = i + diff[d];
				const auto l = j + diff[(d + 1) & 3];
				if (k < 0 || height <= k) continue;
				if (l < 0 || width <= l) continue;
				const auto kl = k * width + l;
				edges.emplace_back(ij, kl, -a[i][j]);
				edges.emplace_back(kl, ij, b[i][j]);
			}
		}
	}
	const auto distance = min_distance(height * width + 1, edges, height * width);
	if (distance.empty() || std::any_of(distance.begin(), distance.end(), [](const long long int a) {return a < 0; })) return {};
	std::vector<std::vector<long long int>> result(height, std::vector<long long int>(width));
	for (auto i = 0; i < height; ++i) {
		for (auto j = 0; j < width; ++j) {
			result[i][j] = distance[i * width + j];
		}
	}
	return result;
}

bool make_and_velify(const bool expected, const int height, const int width, const std::vector<std::vector<int>> a, const std::vector<std::vector<int>> b) {
	const auto result = solve(height, width, a, b);
	if (result.empty()) {
		return !expected;
	}
	if (check(result, a, b)) {
		return expected;
	}
	return false;
}
void check(const int seed) {
	constexpr std::array<int, 4> diff{ 0, 1, 0, -1 };
	std::uniform_int_distribution<int> size(2, 5);
	std::uniform_int_distribution<int> value(1, 30);
	std::mt19937 random(seed);
	const auto height = size(random);
	const auto width = size(random);
	std::vector<std::vector<long long int>> result(height, std::vector<long long int>(width));
	for (auto i = 0; i < height; ++i) {
		for (auto j = 0; j < width; ++j) {
			result[i][j] = value(random);
		}
	}
	std::vector<std::vector<int>> a(height, std::vector<int>(width)), b(height, std::vector<int>(width));
	for (auto i = 0; i < height; ++i) {
		for (auto j = 0; j < width; ++j) {
			long long int min_neighbor{ INT_MAX }, max_neighbor{ INT_MIN };
			const auto tij = result[i][j];
			for (auto d = 0; d < 4; ++d) {
				const auto k = i + diff[d];
				const auto l = j + diff[(d + 1) & 3];
				if (k < 0 || height <= k) continue;
				if (l < 0 || width <= l) continue;
				min_neighbor = std::min(min_neighbor, result[k][l]);
				max_neighbor = std::max(max_neighbor, result[k][l]);
			}
			const auto max_a = tij - max_neighbor;
			const auto min_b = tij - min_neighbor;
			std::uniform_int_distribution<int> a_dist(std::min(0LL, max_a - 1), max_a), b_dist(min_b, 100);
			a[i][j] = a_dist(random);
			b[i][j] = b_dist(random);
			assert(a[i][j] <= b[i][j]);
		}
	}
	if (!check(result, a, b)) {
		throw 0;
	}
	if (make_and_velify(true, height, width, a, b)) {
		std::cout << "OK: " << seed << '\n';
	}
	else {
		std::cout << "NG: " << seed << '\n';
		throw 0;
	}
}
void test() {
	std::mt19937 rand(0);
	std::uniform_int_distribution<int> value(0, 10000);
	for (auto _t = 0; _t < 100; ++_t) {
		const auto seed = value(rand);
		std::cout << seed << '\n';
		check(seed);
	}
}
int main() {
	int height, width; std::cin >> height >> width;
	std::vector<std::vector<int>> a(height, std::vector<int>(width)), b(height, std::vector<int>(width));
	for (auto& line : a) {
		for (auto& cell: line) {
			std::cin >> cell;
		}
	}
	for (auto& line : b) {
		for (auto& cell : line) {
			std::cin >> cell;
		}
	}
	const auto result = solve(height, width, a, b);
	if (result.empty()) {
		std::cout << "-1\n";
	}
	else {
		for (auto i = 0; i < height; ++i) {
			for (auto j = 0; j < width; ++j) {
				if (j > 0) std::cout << ' ';
				std::cout << result[i][j];
			}
			std::cout << '\n';
		}
	}
}
accuracy: 1
time_ms: 80
memory_kb: 3696
final_rank: 12

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define SIZE 55


struct Info{
	void set(int arg_from,int arg_to,ll arg_cost){
		from = arg_from;
		to = arg_to;
		cost = arg_cost;
	}
	int from,to;
	ll cost;
};


int H,W;
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
ll A[SIZE][SIZE],B[SIZE][SIZE],min_dist[SIZE*SIZE];
Info info[SIZE*SIZE*8];

bool rangeCheck(int row,int col){

	return row >= 0 && row <= H-1 && col >= 0 && col <= W-1;
}

int getNUM(int row,int col){

	return W*row + col;
}

int main(){

	scanf("%d %d",&H,&W);

	int V =H*W;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&A[row][col]);
		}
	}
	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&B[row][col]);
		}
	}

	int num_e = 0;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			int from = getNUM(row,col);
			for(int i = 0; i < 4; i++){
				int adj_row = row+diff_row[i];
				int adj_col = col+diff_col[i];
				if(!rangeCheck(adj_row,adj_col))continue;

				int to = getNUM(adj_row,adj_col);

				info[num_e++].set(from,to,-A[row][col]);
				info[num_e++].set(to,from,B[row][col]);
			}
		}
	}

	for(int i = 0; i < V; i++){

		min_dist[i] = HUGE_NUM;
	}

	min_dist[0] = 0;

	bool FLG = true,updated;
	Info tmp;

	for(int i = 0; i < V; i++){
		updated = false;
		for(int k = 0; k < num_e; k++){
			tmp = info[k];
			if(min_dist[tmp.from] != HUGE_NUM && min_dist[tmp.to] > min_dist[tmp.from] + tmp.cost){
				min_dist[tmp.to] = min_dist[tmp.from] + tmp.cost;

				updated = true;
				if(i == V-1){
					FLG = false;
					break;
				}
			}
		}
		if(!updated)break;
		if(!FLG)break;
	}

	if(!FLG){
		printf("-1\n");
		return 0;
	}

	ll mini = HUGE_NUM;
	for(int i = 0; i < V; i++){

		mini = min(mini,min_dist[i]);
	}
	for(int i = 0; i < V; i++){

		min_dist[i] += abs(mini);
		if(min_dist[i] < 0 || min_dist[i] > 1000000000){

			printf("-1\n");
			return 0;
		}
	}

	for(int i = 0; i < V; i++){
		if(i%W == 0){

			printf("%lld",min_dist[i]);
		}else{

			printf(" %lld",min_dist[i]);
		}
		if((i+1)%W == 0){

			printf("\n");
		}
	}

	return 0;
}
accuracy: 1
time_ms: 100
memory_kb: 3432
final_rank: 10

code_snippet: #include<bits/stdc++.h>
typedef long long int ll;
typedef unsigned long long int ull;
#define BIG_NUM 2000000000
#define HUGE_NUM 4000000000000000000 //オーバーフローに注意
#define MOD 1000000007
#define EPS 0.000000001
using namespace std;


#define SIZE 55

struct Edge{
	void set(int arg_from,int arg_to,int arg_cost){
		from = arg_from;
		to = arg_to;
		cost = arg_cost;
	}
	int from,to,cost;
};

int H,W;
int diff_row[4] = {-1,0,0,1},diff_col[4] = {0,-1,1,0};
ll A[SIZE][SIZE],B[SIZE][SIZE],min_dist[SIZE*SIZE];
Edge edge[SIZE*SIZE*8];

bool rangeCheck(int row,int col){

	return row >= 0 && row <= H-1 && col >= 0 && col <= W-1;
}

int getNUM(int row,int col){

	return W*row + col;
}

int main(){

	scanf("%d %d",&H,&W);

	int V = H*W;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&A[row][col]);
		}
	}
	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			scanf("%lld",&B[row][col]);
		}
	}

	int num_e = 0;

	for(int row = 0; row < H; row++){
		for(int col = 0; col < W; col++){

			int from = getNUM(row,col);

			for(int i = 0; i < 4; i++){

				int adj_row = row+diff_row[i];
				int adj_col = col+diff_col[i];
				if(!rangeCheck(adj_row,adj_col))continue;

				int to = getNUM(adj_row,adj_col);

				edge[num_e++].set(from,to,-A[row][col]);
				edge[num_e++].set(to,from,B[row][col]);
			}

		}
	}


	min_dist[0] = 0;
	for(int i = 1; i < V; i++){

		min_dist[i] = HUGE_NUM;
	}


	bool FLG = true,updated;
	Edge tmp;

	for(int i = 0; i < V; i++){
		updated = false;
		for(int k = 0; k < num_e; k++){
			tmp = edge[k];
			if(min_dist[tmp.from] != HUGE_NUM && min_dist[tmp.to] > min_dist[tmp.from] + tmp.cost){
				min_dist[tmp.to] = min_dist[tmp.from] + tmp.cost;

				updated = true;
				if(i == V-1){
					FLG = false;
					break;
				}
			}
		}
		if(!updated)break;
		if(!FLG)break;
	}

	if(!FLG){
		printf("-1");
		return 0;
	}

	ll mini = HUGE_NUM;

	for(int i = 0; i < V; i++){

		mini = min(mini,min_dist[i]);
	}

	for(int i = 0; i < V; i++){

		min_dist[i] += abs(mini);
		if(min_dist[i] > 1000000000){

			printf("-1\n");
			return 0;
		}
	}

	for(int i = 0; i < V; i++){

		if(i%W == 0){

			printf("%lld",min_dist[i]);
		}else{

			printf(" %lld",min_dist[i]);
		}
		if((i+1)%W == 0){

			printf("\n");
		}
	}

	return 0;
}
accuracy: 1
time_ms: 90
memory_kb: 3492
final_rank: 9