枚举之讨厌的青蛙
2017-10-02 本文已影响9人
cherryleechen
问题描述
![](https://img.haomeiwen.com/i8016875/b79f6a8af0c10592.png)
![](https://img.haomeiwen.com/i8016875/278f0b6ab40d287f.png)
![](https://img.haomeiwen.com/i8016875/8742a199c2031769.png)
![](https://img.haomeiwen.com/i8016875/bb695bee9d7bd4ee.png)
题目要求
![](https://img.haomeiwen.com/i8016875/9fc27ee93b6db6bb.png)
程序输入
![](https://img.haomeiwen.com/i8016875/5a1fb515557493d8.png)
程序输出
![](https://img.haomeiwen.com/i8016875/b521072b721fb848.png)
样例
![](https://img.haomeiwen.com/i8016875/8436a4d6e890f1b3.png)
解题思路
![](https://img.haomeiwen.com/i8016875/1a5d736a4146e3db.png)
![](https://img.haomeiwen.com/i8016875/c5e83b4fd196094c.png)
![](https://img.haomeiwen.com/i8016875/f62af41d7ed31ba7.png)
![](https://img.haomeiwen.com/i8016875/89d107d7993043ed.png)
注意
![](https://img.haomeiwen.com/i8016875/b6db7e8495dc9180.png)
![](https://img.haomeiwen.com/i8016875/7bccd237e78c63a7.png)
![](https://img.haomeiwen.com/i8016875/fb150a0fe8e8c2ee.png)
程序实现
#include<iostream>
#include<algorithm>
using namespace std;
int R,C,N;//行数,列数,被踩水稻数
struct Plant{
int x;
int y;
Plant(){}
Plant(int m,int n){x=m;y=n;}
};
bool operator < (const Plant& p1,const Plant& p2){
if(p1.x==p2.x) return p1.y<p1.y;
return p1.x<p2.x;
}
int main(){
cin>>R>>C;//输入行数和列数,x方向是上下,y方向是左右
cin>>N;
int i,j,dX,dY,pX,pY,maxs=2,steps;
Plant plant[N];
for(i=0;i<N;i++)
cin>>plant[i].x>>plant[i].y;
sort(plant,plant+N);//将plant按x坐标从小到大排序,x坐标相同的按y坐标从小到大排序
for(i=0;i<N-2;i++)//plant[i]是第一个点
for(j=i+1;j<N-1;j++)//plant[j]是第二个点
{
dX=plant[j].x-plant[i].x;
dY=plant[j].y-plant[i].y;
pX=plant[i].x-dX;
pY=plant[i].y-dY;
if(pX<=R and pX>=1 and pY<=C and pY>=1)
continue;//第一点的前一点在田里,说明第二点选择不合理,导致步长太小
if(plant[i].x+(maxs-1)*dX>R)
break;//最小步长下,x方向过早越界,说明第一点不合理
if(plant[i].y+(maxs-1)*dY>C or plant[i].y+(maxs-1)*dY<1)
continue;//y方向过早越界,第二点选择不合理
steps=3;
while(pX+dX*steps<=R and pX+dX*steps>=1 and pY+dY*steps<=C and pY+dY*steps>=1){
//看看从这两点出发一共能走多少步
Plant tmpPlant(pX+dX*steps,pY+dY*steps);
if(binary_search(plant+j+1,plant+N,tmpPlant)) steps++;
else {//每一步都必须在田里,否则就不是一条合理路径
steps=0;break;}
}
if(maxs<steps-1) maxs=steps-1;
}
if(maxs==2) cout<<0<<endl;
else cout<<maxs<<endl;
return 0;
}
运行结果
![](https://img.haomeiwen.com/i8016875/1ba0c177f9664c2e.png)
小结
![](https://img.haomeiwen.com/i8016875/8d700eb567e74ab3.png)