poj-1054-The Troublesome Frog-搜索+剪枝

直接暴力搜索:

24796K 2219MS
优化剪枝:

24796K 1032MS

#include<stdio.h>
#include<string.h>
#include<iostream>
#include<algorithm>
using namespace std;
#define N 5001
struct list
{
	int x;
	int y;
	bool friend operator < (list a,list b)
	{
		if(a.x!=b.x)return a.x<b.x;
		return a.y<b.y;
	}
}node[N];
int r,c,n;
bool maps[N][N];
int pan(int x,int y)
{
	if(x<1||x>r||y<1||y>c)return 0;
	return 1;
}
int main()
{
	cin>>r>>c;
	cin>>n;
	int i,j;
	memset(maps,0,sizeof(maps));
	for(i=0;i<n;i++)
	{
		scanf("%d%d",&node[i].x,&node[i].y);
		maps[node[i].x][node[i].y]=1;
	}
	sort(node,node+n);
	int maxn;
	maxn=2;
	for(i=0;i<n;i++)
	{
		int sum;
		sum=0;
		for(j=i+1;j<n;j++)
		{
			int fx;
			int fy;
			fx=node[j].x-node[i].x;
			fy=node[j].y-node[i].y;
			if(pan(node[i].x-fx,node[i].y-fy))continue;
			if(node[i].x+maxn*fx>r||node[i].y+maxn*fy>c||node[i].y+maxn*fy<1)continue;//无法比当前依存的最大值还大
			int tx,ty;
			tx=node[j].x;
			ty=node[j].y;
			sum=1;
			while(pan(tx,ty))
			{
				if(maps[tx][ty]==0)break;
				sum++;
				tx=tx+fx;
				ty=ty+fy;
			}
			if(!pan(tx,ty))
			{
				maxn=max(maxn,sum);
			}
		}
	}
	if(maxn>=3)
	cout<<maxn<<endl;
	else cout<<"0"<<endl;
	return 0;
}
	
			
				
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
			
	
	














你可能感兴趣的:(poj-1054-The Troublesome Frog-搜索+剪枝)