您的位置:首页 > 其它

SCU 4488 king's trouble II(dp||枚举)

2017-03-18 18:11 127 查看
king's trouble II

Description

Long time ago, a king occupied a vast territory.
Now there is a problem that he worried that he want to choose a largest square of his territory to build a palace.
Can you help him?

For simplicity, we use a matrix to represent the territory as follows:
0 0 0 0 0
0 1 0 1 0
1 1 1 1 0
0 1 1 0 0
0 0 1 0 0

Every single number in the matrix represents a piece of land, which is a 1*1 square
1 represents that this land has been occupied
0 represents not

Obviously the side-length of the largest square is 2


Input

The first line of the input contains a single integer t (1≤t≤5) — the number of cases.
For each case
The first line has two integers N and M representing the length and width of the matrix
Then M lines follows to describe the matrix
1≤N,M≤1000

Output

For each case output the the side-length of the largest square

Sample Input

2
5 5
0 0 0 0 0
0 1 0 1 0
1 1 0 1 0
0 1 1 0 0
0 0 1 0 0
5 5
0 0 0 0 0
0 1 0 1 0
1 1 1 1 0
0 1 1 0 0
0 0 1 0 0

Sample Output

1
2

ps:这一题初看的时候真的是没有思路,看了别人的代码才想起可以dp,还可以枚举长度

代码(dp):
#include<stdio.h>
#include<string.h>

#define maxn   1000+10
#define max(a,b) (a>b?a:b)
#define min(a,b) (a<b?a:b)
int dp[maxn][maxn];
int n,m,ans;

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
memset(dp,0,sizeof(dp));
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)

d500
scanf("%d",&dp[i][j]);
ans=0;
for(int i=1; i<n; i++)
for(int j=1; j<m; j++)
{
if(dp[i][j]!=0)
dp[i][j]=min(dp[i-1][j],min(dp[i][j-1],dp[i-1][j-1]))+1;
ans=max(ans,dp[i][j]);
}
printf("%d\n",ans);
}
return 0;
}


代码(枚举):
#include<stdio.h>
#include<string.h>

#define maxn 1000+10
#define min(a,b) (a<b?a:b)
#define max(a,b) (a>b?a:b)
int a[maxn][maxn];
int n,m;

int judge(int x,int y,int k)
{
for(int i=x; i<=x+k; i++)//判断第k列是否符合条件
if(!a[i][y+k])
return 0;
for(int i=y; i<=y+k; i++)//判断第k行是否符合条件
if(!a[x+k][i])
return 0;
return 1;
}

int main()
{
int t;
scanf("%d",&t);
while(t--)
{
scanf("%d%d",&n,&m);
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
scanf("%d",&a[i][j]);
int ans=0,k;
for(int i=0; i<n; i++)
for(int j=0; j<m; j++)
if(a[i][j])
{
int ed=min(n-i,m-j);//到最底端还有多长
for(k=1; k<ed; k++)//枚举长度
if(!judge(i,j,k))
break;
ans=max(ans,k);
}
printf("%d\n",ans);
}
return 0;
}


总结:这一题的做法和那种到终点有多少条路一样,都是求最大或者是最多的,所以可以通过上一步的状态来得到下一步的状态,因此用dp
而枚举我觉得则是这种找最大面积或者是最大边长类型的通解
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: