openjudge 2812恼人的青蛙

#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstdlib>
using namespace std;
int r,c,n;
struct PLANT {
	int x,y;
};
PLANT plants[5001];
PLANT plant;
bool cmp(PLANT plant1,PLANT plant2){
	if(plant1.x == plant2.x){
		return plant1.y < plant2.y;
	}else {
		return plant1.x < plant2.x;
	}
}
int searchPath(PLANT secPlant,int dX,int dY){
	PLANT plant;
	int steps = 2;
	
	plant.x = secPlant.x + dX;
	plant.y = secPlant.y + dY;
	while(plant.x <= r && plant.x >= 1 && plant.y <= c && plant.y >= 1){
		if(!binary_search(plants,plants+n,plant,cmp)){//二分查找 
			steps = 0;
			break;
		}
		plant.x += dX;
		plant.y += dY;
		steps++;
	}
	return steps;
}
int main()
{
	int i,j,dX,dY,pX,pY,steps,mmax=2;
	cin >> r >> c;
	cin >> n;
	for(i=0;i<n;i++){
		cin >> plants[i].x >> plants[i].y;
	}
	sort(plants,plants+n,cmp);
	for(i=0;i<n-2;i++){
		for(j=i+1;j<n-1;j++){
			dX = plants[j].x - plants[i].x;
			dY = plants[j].y - plants[i].y;
			pX = plants[i].x - dX;
			pY = plants[i].y - dY;
			//说明青蛙的第一步在稻田之内 
			if(pX <=r && pX >= 1 && pY <= c && pY >= 1){
				continue;
			}
			//优化,当前位置 * 当前最大步数是否超出稻田范围 
			if(plants[i].x + mmax * dX > r){
				break;
			}
			pY = plants[i].y + mmax * dY;
			if(pY > c || pY < 1){
				continue;
			}
			steps = searchPath(plants[j],dX,dY);
			if(steps > mmax){
				mmax = steps;
			}
		}
	}
	if(mmax == 2){
		mmax = 0;
	}
	cout << mmax;
	return 0;
}

经典题目,完全不剪枝时间接近1000MS。剪枝后100MS. 此题还可以继续剪枝,比如倒序搜索,继续将选取的不合格的两个点剪掉。

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值