CodeForces - 1080E (2020.3.29训练I题)

Problem
Sonya had a birthday recently. She was presented with the matrix of size n×m and consist of lowercase Latin letters. We assume that the rows are numbered by integers from 1 to n from bottom to top, and the columns are numbered from 1 to m from left to right.

Let’s call a submatrix (i1,j1,i2,j2) (1≤i1≤i2≤n;1≤j1≤j2≤m) elements aij of this matrix, such that i1≤i≤i2 and j1≤j≤j2. Sonya states that a submatrix is beautiful if we can independently reorder the characters in each row (not in column) so that all rows and columns of this submatrix form palidroms.

Let’s recall that a string is called palindrome if it reads the same from left to right and from right to left. For example, strings abacaba,bcaacb,a are palindromes while strings abca,acbba,ab are not.

Help Sonya to find the number of beautiful submatrixes. Submatrixes are different if there is an element that belongs to only one submatrix.

Input
The first line contains two integers

  • List item

n and m (1≤n,m≤250) — the matrix dimensions.

Each of the next n lines contains m lowercase Latin letters.

Output
Print one integer — the number of beautiful submatrixes.

题意:给定一个n*m的矩阵,求其中有多少个子矩阵是好矩阵(好矩阵要满足每行通过重排列成为回文串,同时每列也是回文串)

判断每行能不能重排成回文串很简单,只要个数为奇数的字母个数不大于一就可以
而列方向上该如何处理呢,这时候就要用到马拉车算法了
能够匹配的行(相等行)一定是完全相同的(即每种字母的个数是完全一样的),以此为基础引入列方向上的manachar,可以理解为把每行字符串当做一个字符,列方向上就是一个长为n的字符串,接下来就是纯粹的拉车了,不停的更新ans即可

AC代码:

#include
#include
#include
using namespace std;
typedef long long ll;
const ll maxn = 255;
char s[maxn][maxn];
ll a[maxn << 1][26];
ll p[maxn << 1];
ll tot[maxn << 1];
ll ans = 0;
ll n, m;
bool judge(ll x, ll y)
{
	if (tot[x] > 1 || tot[y] > 1)
		return false;
	for( int i = 0; i < 26; i++)
	{
		if (a[x][i] != a[y][i])
			return false;
	}
	return true;
}
void manachar()
{
	ll len = n;
	len++;
	len <<= 1;
	ll mx =0 , id = 0;
	for (int i = 0; i < len; i++)
	{
		if (mx > i)
			p[i] = min(p[id * 2 - i], mx - i);
		else 
			p[i] = 1;
		while (i - p[i] > 0 && i + p[i] < len && judge(i - p[i], i + p[i]))
		{
			p[i]++;
		}
		if (tot[i] > 1) p[i] = 1;
		if(mx < p[i] + i)
		{
			mx = p[i] + i;
			id = i;
		}
		ans += p[i] / 2;
	}
}
int main()
{
	scanf("%d%d",&n, &m);
	for (int i = 0; i < n; i++)
	{
		scanf("%s", s[i]);
	}
	/*
		将所有子矩阵情况考虑全
		所以接下来的for大循环j代表每种大情况的起点列
		每次大情况后要自动初始化
	*/
	for (int j = 0; j < m; j++)
	{
		for (int i = 0; i < n; i++)//初始化
		{
			tot[(i + 1) << 1] = 0;
			for (int k = 0; k < 26; k++)
			{
				a[(i + 1) << 1][k] = 0;
			}
		}
		for (int i = j; i < m; i++)
		{
			for (int k = 0; k < n; k++)//更新每行每种字母出现次数,奇出现的数的个数
			{
				if(a[(k + 1) << 1][s[k][i] - 'a'] & 1) tot[(k + 1) << 1]--;
				else tot[(k + 1) << 1]++;
				a[(k + 1) << 1][s[k][i] - 'a']++;
			}
			manachar();//在新列加入前,跳入一次manachar更新ans
		}
	}
	cout << ans << endl;
}

你可能感兴趣的:(CodeForces - 1080E (2020.3.29训练I题))