【洛谷 P1736】创意吃鱼法

题目背景
感谢@throusea 贡献的两组数据

题目描述
回到家中的猫猫把三桶鱼全部转移到了她那长方形大池子中,然后开始思考:到底要以何种方法吃鱼呢(猫猫就是这么可爱,吃鱼也要想好吃法 ^_*)。她发现,把大池子视为01矩阵(0表示对应位置无鱼,1表示对应位置有鱼)有助于决定吃鱼策略。

在代表池子的01矩阵中,有很多的正方形子矩阵,如果某个正方形子矩阵的某条对角线上都有鱼,且此正方形子矩阵的其他地方无鱼,猫猫就可以从这个正方形子矩阵“对角线的一端”下口,只一吸,就能把对角线上的那一队鲜鱼吸入口中。

猫猫是个贪婪的家伙,所以她想一口吃掉尽量多的鱼。请你帮猫猫计算一下,她一口下去,最多可以吃掉多少条鱼?

输入输出格式
输入格式:
有多组输入数据,每组数据:

第一行有两个整数n和m(n,m≥1),描述池塘规模。接下来的n行,每行有m个数字(非“0”即“1”)。每两个数字之间用空格隔开。

对于30%的数据,有n,m≤100

对于60%的数据,有n,m≤1000

对于100%的数据,有n,m≤2500

输出格式:
只有一个整数——猫猫一口下去可以吃掉的鱼的数量,占一行,行末有回车。

输入输出样例
输入样例#1:
4 6
0 1 0 1 0 0
0 0 1 0 1 0
1 1 0 0 0 1
0 1 1 0 1 0
输出样例#1:
3
说明
右上角的

1 0 0
0 1 0
0 0 1
这道题和之前做过的最大正方形十分的类似。
状态转移方程为 d p [ i ] [ j ] = m i n ( d p [ i 1 ] [ j 1 ] | | d p [ i 1 ] [ j + 1 ] , s 1 [ i ] [ j ] , s 2 [ i ] [ j ] ) + 1
其中 d p [ i ] [ j ] 代表以 a [ i ] [ j ] 为右下角(左下角)的最大正方形的边长 s 1 [ i ] [ j ] 表示以a[i][j]为
左端点往右(往左)延伸的都是0的最大长度,两次dp即可。

#include<bits/stdc++.h>
using namespace std;
const int maxn = 2550;
int dp[maxn][maxn];
int s1[maxn][maxn];
int s2[maxn][maxn];
int maze[maxn][maxn];
int main(){
    ios::sync_with_stdio(0);
    int n,m;
    cin>>n>>m;
    int s;
    memset(s1,0,sizeof(s1));
    memset(s2,0,sizeof(s2));
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++){
        s=0;
        for(int j=1;j<=m;j++){
            cin>>maze[i][j];
            if(maze[i][j]==0){
                s++;
            }
            else{
                s1[i][j]=s;
                s=0;
            }
        }
    }
    for(int j=1;j<=m;j++){
        s=0;
        for(int i=1;i<=n;i++){
            if(maze[i][j]==0){
                s++;
            }
            else{
                s2[i][j]=s;
                s=0;
            }
        }
    }
    int ans=0;
    for(int i=1;i<=n;i++){
        for(int j=1;j<=m;j++){
            if(maze[i][j]==1){
                dp[i][j]=min(dp[i-1][j-1],min(s1[i][j],s2[i][j]))+1;
                ans=max(ans,dp[i][j]);
            }
        }
    }
    memset(s1,0,sizeof(s1));
    memset(dp,0,sizeof(dp));
    for(int i=1;i<=n;i++){
        s=0;
        for(int j=m;j>=1;j--){
            if(maze[i][j]==0){
                s++;
            }
            else{
                s1[i][j]=s;
                s=0;
            }
        }
    }
    for(int i=1;i<=n;i++){
        for(int j=m;j>=1;j--){
            if(maze[i][j]){
                dp[i][j]=min(dp[i-1][j+1],min(s2[i][j],s1[i][j]))+1;
                ans=max(ans,dp[i][j]);
            }
        }
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/duanghaha/article/details/81627581