题目描述
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.
输入
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).
输入
4 5
abcde
fGhij
klmno
pqrst
输出
150
说明
For sample 2, the grid has 150 nonempty subrectangles, and all of them are sudoku-like.
题意:输入一个只包含52种字符的矩阵,问有多少个子矩形,满足:
1,任意一行的字母互不相同。
2,任意一列的字母互不相同。
思路:预处理每个点向左到达的最大长度与向上到达的最大长度,然后暴力搞。
对我来说这个暴力很有技术含量,要学习
#include <set>
#include <map>
#include <deque>
#include <stack>
#include <queue>
#include <time.h>
#include <vector>
#include <string>
#include <math.h>
#include <cstring>
#include <cstdlib>
#include <stdio.h>
#include <iomanip>
#include <iostream>
#include <algorithm>
#define PI acos(-1)
#define LL long long
#define inf 999999
#define ull unsigned long long
using namespace std;
char s[1005][1005];
int lmax[1005][1005],pos[200],umax[1005][1005],len[1005],n,m;
void solve()
{
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[s[i][j]]);
pos[s[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[s[i][j]]);
pos[s[i][j]]=i;
}
}
long long ans=0;
for(int r=1;r<=m;r++)
{
memset(len,0,sizeof len);
for(int d=1;d<=n;d++)
{
for(int i=0;i<lmax[d][r];i++)
{
len[i]=min(umax[d][r-i],len[i]+1);
if(i) len[i]=min(len[i],len[i-1]);
ans+=len[i];
}
for(int i=lmax[d][r];i<=54;i++) len[i]=0;
}
}
printf("%lld\n",ans);
}
int main()
{
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++) scanf("%s",s[i]+1);
solve();
return 0;
}