This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MOD = 1e9 + 7;
const int MAXN = (int)2007;
const int infint = (int)1e9;
const ll inf = (ll)1e18;
ll n, m, up[MAXN][MAXN], lft[MAXN], rgt[MAXN];
char c[MAXN][MAXN];
ll sum(ll x)
{
	return x * (x + 1) / 2;
}
int main()
{
	ios::sync_with_stdio(false);
	cin.tie(0); cout.tie(0);
	cin >> n >> m;
	for (int i = 0; i < n; i++)
		for (int j = 0; j < m; j++)
			cin >> c[i][j];
	for (int j = 0; j < m; j++)
		if(c[0][j] == '#')	
			up[0][j] = 0;
		else
			up[0][j] = -1;
	for (int i = 1; i < n; i++)
		for (int j = 0; j < m; j++)
			if(c[i][j] == '#')
				up[i][j] = i;
			else
				up[i][j] = up[i - 1][j];
	ll ans = 0;
	for (int i = 0; i < n; i++)
	{
		stack<ll> S;
		for (int j = 0; j < m; j++)
		{
			while(!S.empty() && up[i][j] > up[i][S.top()])
				S.pop();
			if(S.empty())
				lft[j] = -1;
			else
				lft[j] = S.top();
			S.push(j);
		}
		while(!S.empty())
			S.pop();
		for (int j = m - 1; j >= 0; j--)
		{
			while(!S.empty() && up[i][j] >= up[i][S.top()])
				S.pop();
			if(S.empty())
				rgt[j] = m;
			else
				rgt[j] = S.top();
			S.push(j);
		}
		for (int j = 0; j < m; j++)
		{
			ll t = i - up[i][j];
			t = sum(t);
			ans += t * (rgt[j] - j) * sum(j - lft[j]);
			ans += t * (j - lft[j]) * sum(rgt[j] - j - 1);
		}
	}
	cout << ans;
}
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... | 
| # | Verdict | Execution time | Memory | Grader output | 
|---|
| Fetching results... |