#include #include #include #include #include #include #include #include #include #include #include #include #define LL long long using namespace std; const int N = 1010; const LL mod = 1LL << 32; int l[N][N], r[N][N], u[N][N], d[N][N], a[N][N]; unsigned int c (unsigned int l, unsigned int r) { return l * (l + 1) / 2 * r + r * (r + 1) / 2 * l - l * r; } int main () { // freopen ("in.txt", "w", stdout); // return 0; // cout << c (1, 1) << endl; // freopen ("in.txt", "r", stdin); int T; cin >> T; while (T--) { int n, m; cin >> n >> m; // for (int i = 1; i <= n; i++) { // for (int j = i; j <= n; j++) { // for (int k = 1; k <= m; k++) { // for (int l = k; l <= m; l++) { // res += cal (i, j, k, l) * () // } // } // } // } // cout << n << m; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { scanf ("%d", &a[i][j]); } } for (int i = 1; i <= n; i++) { a[i][0] = a[i][m + 1] = 0; for (int j = 1; j <= m; j++) { // cout << i << ' ' << j << endl; l[i][j] = j; while (a[i][j] < a[i][l[i][j] - 1]) l[i][j] = l[i][l[i][j] - 1]; } for (int j = m; j >= 1; j--) { // cout << i << ' ' << j << endl; r[i][j] = j; while (a[i][j] < a[i][r[i][j] + 1]) r[i][j] = r[i][r[i][j] + 1]; } } for (int i = 1; i <= m; i++) { a[0][i] = a[n + 1][i] = 1e9; for (int j = 1; j <= n; j++) { // cout << i << ' ' << j << endl; u[j][i] = j; while (a[j][i] > a[u[j][i] - 1][i]) u[j][i] = u[u[j][i] - 1][i]; } for (int j = n; j >= 1; j--) { // cout << i << ' ' << j << endl; d[j][i] = j; while (a[j][i] > a[d[j][i] + 1][i]) d[j][i] = d[d[j][i] + 1][i]; } } unsigned int res = 0; for (int i = 1; i <= n; i++) { for (int j = 1; j <= m; j++) { unsigned int ll = j - l[i][j] + 1, rr = r[i][j] - j + 1, uu = i - u[i][j] + 1, dd = d[i][j] - i + 1; // cout << i << ' ' << j << ' ' << ll << ' ' << rr << ' ' << uu << ' ' << dd << endl; res += c(ll, rr) * c (uu, dd) * a[i][j]; } } cout << res % mod << endl; } }