链接:https://www.nowcoder.com/acm/contest/145/J
来源:牛客网
时间限制:C/C++ 1秒,其他语言2秒
空间限制:C/C++ 32768K,其他语言65536K
Special Judge, 64bit IO Format: %lld
题目描述
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).
示例2
输入
复制
4 5 abcde fGhij klmno pqrst
输出
复制
150
说明
For sample 2, the grid has 150 nonempty subrectangles, and all of them are sudoku-like.
题意:在一个字母矩阵中要寻找横竖都没有重复字母的子矩阵,请问这种矩阵一共有多少个
思路:维护行中每个字母到小于当前位置最长能构成的长度max 维护列中每个字母到小于当前位置最长能构成的长度umax
枚举子矩阵的右下角(i,j)且从当前位置到maxn的位置应该是不上升序列 因为是矩形所以高度要水平
右下角到其中某点可构成的矩形就是当前点的umax
#include<bits/stdc++.h>
using namespace std;
const int maxn = 1005;
int lmax[maxn][maxn],umax[maxn][maxn],len[300],pos[300];
char zdy[maxn][maxn];
int n,m;
int main()
{
while(scanf("%d%d",&n,&m)!=EOF)
{
for(int i=1;i<=n;i++) scanf("%s",zdy[i]+1);
for(int i=1;i<=n;i++)
{
memset(pos,0,sizeof(pos));
for(int j=1;j<=m;j++)
{
lmax[i][j]=min(lmax[i][j-1]+1,j-pos[zdy[i][j]]);
pos[zdy[i][j]]=j;
}
}
for(int j=1;j<=m;j++)
{
memset(pos,0,sizeof(pos));
for(int i=1;i<=n;i++)
{
umax[i][j]=min(umax[i-1][j]+1,i-pos[zdy[i][j]]);
pos[zdy[i][j]]=i;
}
}
long long ans=0;
for(int j=1;j<=m;j++)
{
memset(len,0,sizeof(len));
for(int i=1;i<=n;i++)
{
for(int k=0;k<lmax[i][j];k++)
{
len[k]=min(umax[i][j-k],len[k]+1);
if(k) len[k]=min(len[k-1],len[k]);
ans+=len[k];
}
for(int k=lmax[i][j];k<=54;k++) len[k]=0;
}
}
printf("%lld\n",ans);
}
return 0;
}