Untitled
unknown
plain_text
10 months ago
2.1 kB
4
Indexable
#include <bits/stdc++.h>
using namespace std;
#define fast ios_base::sync_with_stdio(false); cin.tie(NULL)
#define ll long long
void solve() {
int n, m; cin >> n >> m;
ll ans = 0;
int a[n][m];
for (int i = 0 ; i < n; ++i)
for (int j = 0 ; j < m; ++j)
cin >> a[i][j];
ll same_down[n][m];
for (int j = 0; j < m; ++j) {
same_down[n - 1][j] = 1;
for (int i = n - 2; i >= 0; --i) {
if (a[i][j] == a[i + 1][j])
same_down[i][j] = same_down[i + 1][j] + 1;
else same_down[i][j] = 1;
}
}
for (int i = 0 ; i < n; ++i) {
ll cur = 0;
/* find the answer for each sub rectangle
* with a top left corner in row number i
*/
int start = 0;
stack <pair<int ,int>> st;
st.push(make_pair(0, 1));
for (int j = 0; j < m; ++j) {
ll sz = 1;
if (a[i][j] != start) {
while(!st.empty()) st.pop();
cur = same_down[i][j];
ans += cur;
st.push(make_pair(j, 1));
start = a[i][j];
}
else {
int nxt = i;
while(!st.empty() && same_down[i][st.top().first] > same_down[i][j] ) {
pair<int ,int> p = st.top();
st.pop();
sz += p.second;
cur -= 1LL * (same_down[i][p.first] - same_down[i][j]) * p.second;
}
cur += same_down[i][j];
ans += cur;
st.push(make_pair(j, sz));
}
}
}
cout << ans;
}
int main(){
fast;
#ifndef ONLINE_JUDGE
freopen("input.txt", "r", stdin);
freopen("output.txt", "w", stdout);
freopen("Error.txt", "w", stderr);
#endif
int t = 1; cin >> t;
for (int i = 1 ; i <= t; ++i)
{
solve();
if (i != t)
cout << '\n';
}
return 0;
}Editor is loading...
Leave a Comment