【题解】洛谷P2484 打地鼠(模拟)

对于锤子的大小,我们可以枚举。然后模拟对要砸的部分进行操作,对该区域减去砸的地方左上角的数(也就是次数),如果小于零就return false。这样会浪费许多时间。我们可以从大到小枚举锤子,并且只有所有地洞地鼠之和%锤子体积为0时才进行操作,另外,只有当地鼠和÷锤子体积小于等于已得到答案的最小值时才砸。

#include<cstdio>
#include<iostream>
#include<algorithm>
#include<cstring>
#include<cstdlib>
using namespace std;
int m,n;
int a[110][110];
int b[110][110];
int ans;
int sum=0;
int minn=1e9;
int w;
void write()
{
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			cout<<b[i][j]<<' ';
		}
		cout<<endl;
	}
	cout<<"*******************"<<endl;
}
bool hit(int r,int c)
{
	ans=0;
	for(int i=1;i<=m-r+1;i++)
	{
		for(int j=1;j<=n-c+1;j++)
		{
			
			w=b[i][j];
			for(int x=i;x<=i+r-1;x++)
			{
				for(int y=j;y<=j+c-1;y++)
				{
					if(b[x][y]-w<0) return false;
					else
					{
						b[x][y]-=w;
					}
				}
			}
			ans+=w;
	//		cout<<ans<<' '<<r<<' '<<c<<endl;
	//		write(); 
		}
	}
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			if(b[i][j]!=0)
			{
				return false;
			}
		}
	}
	return true; 
}
void copy()
{
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			b[i][j]=a[i][j];
		}
	}
}
int main()
{
	scanf("%d%d",&m,&n);
	for(int i=1;i<=m;i++)
	{
		for(int j=1;j<=n;j++)
		{
			scanf("%d",&a[i][j]);
			sum+=a[i][j];
		}
	}
	copy();
	for(int r=m;r>=1;r--)
	{
		for(int c=n;c>=1;c--)
		{
			if(sum%(r*c)!=0) continue;
			if(sum/(r*c)>minn) continue;
			copy();
			if(hit(r,c)==true)
			{
			//	cout<<ans<<' '<<r<<' '<<c<<endl;
				minn=min(minn,sum/(r*c));
			}
		}
	}
	cout<<minn<<endl;
	return 0;
}

我们可以枚举,在

猜你喜欢

转载自blog.csdn.net/Rem_Inory/article/details/81267396