链接:https://www.nowcoder.com/acm/contest/145/J
来源:牛客网
Sudoku Subrectangles
时间限制: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.
题意:给你一个n*m的矩阵,填满大小写的英文字符,现在让你找有多少个“数独”矩阵,使得在这个矩阵上横向或者竖向上没有相同的字母(区分大小写)
#include<bits/stdc++.h>
using namespace std;
#define ll long long
const int N=1010;
char s[N][N];
int n,m;
int pos[200],lmax[N][N],umax[N][N];// pos为离的最近的当前字符的位置
ll ans;//lmax表示从i行j列开始往左找可以找到的最长拥有各不相同的字符的长度,umax同理为向上
int len[60];//遍历一行行,len保存上一行处理的信息
void init(){
ans=0;
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;
}
}
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++){//从r开始向左遍历,长度为不同的字符的长度
len[i]=min(len[i]+1,umax[d][r-i]);//向上(包括自己)最多可找多少层
if(i)
len[i]=min(len[i],len[i-1]);//与上一层信息对比,保证可形成矩阵
ans+=len[i];
}
for(int i=lmax[d][r];i<=54; i++)//因最多一行一列中最长有52个不同的字符故开到52即可
len[i]=0;//i从lmax开始防止隔层间的信息不对称,比如把第一层信息未清空,第二层较短,第三层再次使用了第一层的长度
}
}
}
int main(){
scanf("%d%d",&n,&m);
for(int i=1; i<=n; i++){
scanf("%s",s[i]+1);
}
init();
printf("%lld\n",ans);
return 0;
}
小菜鸟一枚,如果有哪里写的不对请指出。见谅。