题目描述
One of Farmer John’s fields is particularly hilly, and he wants to purchase a new tractor to drive around on it. The field is described by an N x N grid of non-negative integer elevations (1 <= N <= 500). A tractor capable of moving from one grid cell to an adjacent cell (one step north, east,south, or west) of height difference D costs exactly D units of money.
FJ would like to pay enough for his tractor so that, starting from some grid cell in his field, he can successfully drive the tractor around to visit at least half the grid cells in the field (if the number of total cells in the field is odd, he wants to visit at least half the cells rounded up). Please help him compute the minimum cost necessary for buying a tractor capable of this task.
输入
- Line 1: The value of N.
- Lines 2…1+N: Each line contains N space-separated non-negative integers (each at most 1 million) specifying a row of FJ’s field.
输出 - Line 1: The minimum cost of a tractor that is capable of driving around at least half of FJ’s field.
样例输入 Copy
5
0 0 0 3 3
0 0 0 0 3
0 9 9 3 3
9 9 9 3 3
9 9 9 9 3
样例输出 Copy
3
提示
FJ’s farm is a 5 x 5 grid. The elevations in the first row are 0, 0, 0, 3,and 3, and so on.A tractor of cost 3 is capable of moving between elevation 0 and elevation 3, so it can visit the block of cells at zero elevation as well as the
block of cells at elevation 3. Together, these represent at least half of FJ’s farm.
题意:
FJ有块农田太崎岖了,他要买一辆新拖拉机才能在这里巡视。这块农田由N x N个格子的非负整数表示高度(1<=N<=500)。拖拉机从当前格子走到相邻格子(东、南、西、北四个方向)的代价为高度差D,则FJ驶过这两个格子的拖拉机最少也要值D块钱。
FJ愿意花足够的钱买一辆新的拖拉机使得他能以最小的高度差走遍所有格子的一半(如果格子总数是奇数,那么一半的值为四舍五入的值)。因为FJ很懒,所以他找到你帮他编程计算他最小需要花多少钱买到符合这些要求的拖拉机。
解析:
二分答案,然后dfs一遍,确保符合条件
#include<bits/stdc++.h>
using namespace std;
const int N=550;
int a[N][N];
bool vis[N][N] ;
int n;
int dx[4]={0,1,0,-1};
int dy[4]={1,0,-1,0};
int dfs(int x,int y,int k)
{
vis[x][y]=1;
int res=1;
for(int i=0;i<4;i++)
{
int xx=dx[i]+x;
int yy=dy[i]+y;
if(xx>=0&&yy>=0&&xx<n&&yy<n&&!vis[xx][yy]&&abs(a[xx][yy]-a[x][y])<=k)
res+=dfs(xx,yy,k);
}
return res;
}
bool check(int k)
{
memset(vis,0,sizeof vis);
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
if(!vis[i][j])
if(dfs(i,j,k)*2>=n*n) return 1;
}
return 0;
}
int main()
{
int l=1e9,r=-1;
cin>>n;
int ans;
for(int i=0;i<n;i++)
for(int j=0;j<n;j++)
{
cin>>a[i][j];
l=min(l,a[i][j]);
r=max(r,a[i][j]);
}
// cout<<l<<" "<<r<<endl;
while(l<=r)
{
int mid=l+r>>1;
if(check(mid))
{
r=mid-1;
ans=mid;
}
else l=mid+1;
}
cout<<ans<<endl;
}