POJ 1054 恼人的青蛙 [ 枚举+剪枝 ]

   主要思想就是:先排序(按行号升序,若行号相等就按列号升序);再枚举每两个点,以两个点分别为青蛙所走路线上的第一个点和第二个点(在枚举的过程中的剪枝非常重要);

//   枚举 + 剪枝
#include <stdio.h>
#include <stdlib.h>

int R, C, map[5001][5001];

typedef struct
{
    int x, y;
} COORD;
COORD a[5001];

int compare(const void* a, const void* b)
{                   //按照行号排序,行号相等时按列号升序排序
    COORD *p, *q;
    p = (COORD*)a;
    q = (COORD*)b;
    if (p->x == q->x) return (p->y - q->y);
    else   return (p->x - q->x);
}

int func(int x0, int y0, int dx, int dy)
{
    int X, Y, step=2;

    X = x0 + dx;
    Y = y0 + dy;
    while (X>=1 && X<=R && Y>=1 && Y<=C)
    {
        if (map[X][Y] == 0)
           return 0;
        X += dx;
        Y += dy;
        step++;
    }
    return step;
}

int main()
{
    int n, i, j, step, max=2;
    int dx, dy, x0, y0;

    scanf("%d %d %d", &R, &C, &n);
    for (i=0; i<n; i++)
    {
        scanf("%d %d", &a[i].x, &a[i].y);
        map[a[i].x][a[i].y] = 1; //map[i][j]=1表示(i,j)被塌过
    }
    qsort(a, n, sizeof(COORD), compare);
    for (i=0; i<n-1; i++)
    {
        for (j=i+1; j<n; j++)
        {
            dx = a[j].x - a[i].x;
            dy = a[j].y - a[i].y;
            x0 = a[i].x - dx;
            y0 = a[i].y - dy;
            if (x0>=1 && x0<=R && y0>=1 && y0<=C) continue;//剪枝
            if (a[i].x + max*dx > R) break;//剪枝
            y0 = a[i].y + max*dy;
            if (y0 > C || y0 < 1) continue;//剪枝
            step = func(a[j].x, a[j].y, dx, dy);
            if (step > max) max = step;
        }
    }
    if (max == 2) printf("0/n");
    else printf("%d/n", max);
}


你可能感兴趣的:(c,struct)