poj 1054 The Troublesome Frog

http://poj.org/problem?id=1054

天哪 为什么不超时 受不了啦

直接暴力加优化就可以过呀

枚举两点 找其他合适的点时 控制一下范围

代码及其注释:

#include<iostream>

#include<stdio.h>

#include<string.h>

#include<algorithm>



using namespace std;



const int N=5005;

struct node

{

    int x,y;

}mem[N];

int l[N];//记录x为i是左起位置

int r[N];//记录x为i是右起位置

bool cmp(node a,node b)

{

    if(a.x==b.x)

    return a.y<b.y;

    return a.x<b.x;

}

bool findy(int l,int r,int Y)//二分查找

{

    if(l==-1)

    return false;

    while(l<=r)

    {

        int mid=(l+r)>>1;

        if(mem[mid].y==Y)

        return true;

        if(Y<mem[mid].y)

        {

            r=mid-1;

        }

        else

        {

            l=mid+1;

        }

    }

    return false;

}

int main()

{

   int n,m;

   int w;

   while(scanf("%d %d",&n,&m)!=EOF)

   {

       scanf("%d",&w);

       for(int i=0;i<w;++i)

       {

           scanf("%d %d",&mem[i].x,&mem[i].y);

       }

       sort(mem,mem+w,cmp);

       memset(l,-1,sizeof(l));

       memset(r,-1,sizeof(r));

       for(int i=0;i<w;++i)

       {

           if(l[mem[i].x]==-1)

           {

               l[mem[i].x]=i;//左起位置

           }

           if(i+1==w||mem[i].x!=mem[i+1].x)

           {

               r[mem[i].x]=i;//右起位置

           }

       }

       int ans=0;

       for(int i=0;i<w;++i)

       {

           for(int j=i+1;j<w;++j)

           {

               int xtemp=mem[j].x-mem[i].x;

               int ytemp=mem[j].y-mem[i].y;

               int X=mem[i].x-xtemp;

               int Y=mem[i].y-ytemp;

               if(X>=1&&Y>=1&&Y<=m)//往回找不越界的话 如果找到合适的点说明已经找过这条线路 找不到则不合适

               continue;

               X=mem[j].x+xtemp;

               Y=mem[j].y+ytemp;

               int sum=2;

               while(X<=n&&Y>=1&&Y<=m&&findy(l[X],r[X],Y))

               {

                   ++sum;

                   X=X+xtemp;

                   Y=Y+ytemp;

               }

               if(X>n||Y<1||Y>m)//必须已经越界

               ans=max(ans,sum);

           }

       }

       if(ans<3)

       ans=0;

       printf("%d\n",ans);

   }

   return 0;

}

  

 

你可能感兴趣的:(poj)