蓝桥杯算法训练——暗恋 (简单DP)

版权声明:Dream_dog专属 https://blog.csdn.net/Dog_dream/article/details/88085089

问题描述


  同在一个高中,他却不敢去找她,虽然在别人看来,那是再简单不过的事。暗恋,是他唯一能做的事。他只能在每天课间操的时候,望望她的位置,看看她倾心的动作,就够了。操场上的彩砖啊,你们的位置,就是他们能够站立的地方,他俩的关系就像砖与砖之间一样固定,无法动摇。还记得当初铺砖的工人,将整个操场按正方形铺砖(整个操场可视为R行C列的矩阵,矩阵的每个元素为一块正方形砖块),正方形砖块有两种,一种为蓝色,另一种为红色。我们定义他和她之间的“爱情指标”为最大纯色正方形的面积,请你写一个程序求出“爱情指标”。

输入格式

  第一行两个正整数R和C。
  接下来R行C列描述整个操场,红色砖块用1来表示,蓝色砖块用0来表示。

输出格式

  一个数,表示他和她之间的“爱情指标”。

样例输入

5 8
0 0 0 1 1 1 0 1
1 1 0 1 1 1 1 1
0 1 1 1 1 1 0 1
1 0 1 1 1 1 1 0
1 1 1 0 1 1 0 1

样例输出

9

数据规模和约定

  40%的数据R,C<=10;
  70%的数据R,C<=50;
  100%的数据R,C<=200;


题解:每次记录该位置能形成的的最大面积,设操场为tmap在x, y位置的最大面积dp[x][y]:

如果tmap[x-1][y-1]!=tmap[x][y]   说明dp[x][y]=1;

否则只需要判断从x, y出发向左和向上的最短距离是多少。在于tmap[x-1][y-1]的边长进行判断就好。


#include<cstdio>
#include<algorithm>
#include<cstdlib>
#include<iostream>
#include<string>
#include<cstring>
#include<map>
#include<cmath>

#define clr(a,b) memset(a,b,sizeof(a))
using namespace std;
typedef long long ll;
const int maxnn=200+2;
int r,c,tmap[maxnn][maxnn],dp[maxnn][maxnn];
int getS(int x, int y)
{
	if (tmap[x][y] != tmap[x - 1][y - 1]) { dp[x][y] = 1; return dp[x][y]; }
	int i=1, tlen = 1, ttlen = sqrt(dp[x - 1][y - 1]);
	for (; x - i > 0; ++i)
	{
		if (tmap[x-i][y] != tmap[x][y]) {  break; }
	}
	tlen = i - 1; i = 1;
	for (; y - i > 0; ++i)
	{
		if (tmap[x][y-i] != tmap[x][y]) {  break; }
	}
	tlen = min(i - 1, tlen);
	if (ttlen > tlen) { dp[x][y] = (tlen + 1)*(tlen + 1); }
	else { dp[x][y] = (ttlen + 1)*(ttlen + 1); }
	return dp[x][y];
}
int main()
{
    //freopen("input1.txt","r",stdin);
    while(cin>>r>>c)
    {
        clr(tmap,-1);
        int ans=0;
        for(int i=1;i<=r;++i)
        {
            for(int j=1;j<=c;++j)
            {
                cin>>tmap[i][j];
                ans=max(ans,getS(i,j));
            }
        }
        cout<<ans<<endl;
    }
    return 0;
}

猜你喜欢

转载自blog.csdn.net/Dog_dream/article/details/88085089