链接:https://www.nowcoder.com/acm/contest/145/J
来源:牛客网
You have a n * m grid of characters, where each character is an English letter (lowercase or uppercase, which means there are a total of 52 different possible letters).
A nonempty subrectangle of the grid is called sudoku-like if for any row or column in the subrectangle, all the cells in it have distinct characters.
How many sudoku-like subrectangles of the grid are there?
输入描述:
The first line of input contains two space-separated integers n, m (1 ≤ n, m ≤ 1000). The next n lines contain m characters each, denoting the characters of the grid. Each character is an English letter (which can be either uppercase or lowercase).
输出描述:
Output a single integer, the number of sudoku-like subrectangles.
示例1
输入
复制
2 3 AaA caa
输出
复制
11
说明
For simplicity, denote the j-th character on the i-th row as (i, j). For sample 1, there are 11 sudoku-like subrectangles. Denote a subrectangle by (x1, y1, x2, y2), where (x1, y1) and (x2, y2) are the upper-left and lower-right coordinates of the subrectangle. The sudoku-like subrectangles are (1, 1, 1, 1), (1, 2, 1, 2), (1, 3, 1, 3), (2, 1, 2, 1), (2, 2, 2, 2), (2, 3, 2, 3), (1, 1, 1, 2), (1, 2, 1, 3), (2, 1, 2, 2), (1, 1, 2, 1), (1, 3, 2, 3).
预处理出每一个方格向右和向下不出现重复字母的长度。然后进行计算。
#include<bits/stdc++.h>
#include<map>
#define ll long long
using namespace std;
char g[1010][1010];
int R[1010][1010];
int D[1010][1010];
int temp[1010][1010];
int main()
{
int n,m;
while(scanf("%d%d",&n,&m)!=EOF)
{
memset(R,0,sizeof(R));
memset(D,0,sizeof(D));
memset(temp,0,sizeof(temp));
for(int i=0;i<n;i++)
scanf("%s",g[i]);
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
int t=0;
bool mp[52];
memset(mp,0,sizeof(mp));
for(int k=j;k<m;k++)
{
int p;
if(g[i][k]>='a')
{
p=g[i][k]-'a'+26;
}
else
p=g[i][k]-'A';
if(mp[p]==0)
{
t++;
mp[p]=1;
}
else break;
}
R[i][j]=t;
memset(mp,0,sizeof(mp));
t=0;
for(int k=i;k<n;k++)
{
int p;
if(g[k][j]>='a')
{
p=g[k][j]-'a'+26;
}
else
p=g[k][j]-'A';
if(mp[p]==0)
{
t++;mp[p]=1;
}
else break;
}
D[i][j]=t;
}
}
ll ans=0;
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
temp[i][j]=D[i][j];
int l=j+R[i][j];
for(int k=j+1;k<l;k++)
temp[i][k]=min(temp[i][k-1],D[i][k]);//在向下延伸的长度从左到右要递减
ans+=R[i][j];//以a[i][j]为开头第一行的矩形个数
l=i+D[i][j];
int d=j+R[i][j]-1;//第一行向右延伸的所到达的坐标
for(int k=i+1;k<l;k++)
{
d=min(d,j+R[k][j]-1);//在向右延伸的长度从上到下要递减
while(temp[i][d]<k-i+1&&d>=j)//向右延伸到的最大位置d,而a[i][d]的向下延伸到达不了k
{
d--;
}
if(d<j) break;
ans+=d-j+1;
}
}
}
printf("%lld\n",ans);
}
return 0;
}