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. 此题还可以继续剪枝,比如倒序搜索,继续将选取的不合格的两个点剪掉。

猜你喜欢

转载自blog.csdn.net/mokena1/article/details/81412760
今日推荐