Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <bits/stdc++.h>
- using namespace std;
- const long long oo = (1e18) + 7;
- int main()
- {
- freopen("test.inp","r",stdin);
- int n, m;
- cin>>n>>m;
- int a[n][m];
- for (int i = 0;i<n;++i)
- for (int j = 0;j<m;++j) cin>>a[i][j];
- ////////////////////
- long long res = oo;
- int t[2][2];
- int mat[n][m];
- for (int i = 0;i<2;++i){
- t[0][0] = i;
- t[1][1] = 1-i;
- for (int j = 0;j<2;++j){
- t[1][0] = j;
- t[0][1] = 1-j;
- for (int r = 0;r<n;++r)
- for (int c = 0;c<m;++c)
- {
- mat[r][c] = a[r][c];
- }
- // Solve
- long long cnt = 0;
- bool isConnected = (n > 1 && m > 1);
- bool isRunning = true;
- for (int r = 0;r<n;++r){
- for (int c = 0;c<m;++c){
- int prevCol = 0, prevRow = 0;
- if (r>0) prevRow = mat[r-1][c];
- if (c>0) prevCol = mat[r][c-1];
- int NextValue = max(prevCol, prevRow) + 1;
- if (isConnected && NextValue %2 != t[r%2][c%2]) NextValue++;
- if (mat[r][c] == 0)
- mat[r][c] = NextValue;
- else if ((mat[r][c] < NextValue) || (isConnected && mat[r][c] % 2 != NextValue % 2))
- {
- isRunning = false;
- break;
- }
- cnt += mat[r][c];
- }
- if (isRunning == false) {cnt = oo; break;}
- }
- // endl
- res = min(res, cnt);
- }
- }
- if (res == oo) cout << -1; else
- cout << res;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement