#include #include #include using namespace std; const int maxn = 1000 + 5; unsigned int maze[maxn][maxn], s1[maxn], s2[maxn]; int pos[maxn][maxn][4], st[maxn]; int main() { for(unsigned int i = 1; i < maxn; ++i) { s1[i] = s1[i - 1] + i; s2[i] = s2[i - 1] + s1[i]; } int T; scanf("%d", &T); while(T--) { int n, m, top; scanf("%d%d", &n, &m); for(int i = 1; i <= n; ++i) { top = 0; for(int j = 1; j <= m; ++j) { scanf("%u", &maze[i][j]); while(top && maze[i][st[top - 1]] > maze[i][j]) --top; pos[i][j][0] = top ? st[top - 1] : 0; st[top++] = j; } top = 0; for(int j = m; j > 0; --j) { while(top && maze[i][st[top - 1]] > maze[i][j]) --top; pos[i][j][1] = top ? st[top - 1] : m + 1; st[top++] = j; } } // cout << 1 << endl; for(int j = 1; j <= m; ++j) { top = 0; for(int i = 1; i <= n; ++i) { while(top && maze[st[top - 1]][j] < maze[i][j]) --top; pos[i][j][2] = top ? st[top - 1] : 0; st[top++] = i; } top = 0; for(int i = n; i > 0; --i) { while(top && maze[st[top - 1]][j] < maze[i][j]) --top; pos[i][j][3] = top ? st[top - 1] : n + 1; st[top++] = i; } } unsigned ans = 0; for(int i = 1; i <= n; ++i) { for(int j = 1; j <= m; ++j) { int l = j - pos[i][j][0], r = pos[i][j][1] - j, u = i - pos[i][j][2], d = pos[i][j][3] - i; // cout << i << ' ' << j << ' ' << l << ' ' << r << ' ' << u << ' ' << d << endl; ans += maze[i][j] * (s2[u + d - 1] - s2[u - 1] - s2[d - 1]) * (s2[l + r - 1] - s2[l - 1] - s2[r - 1]); // cout << ans << endl; } } printf("%u\n", ans); } return 0; }