POJ 1054 惱人的青蛙 [ 枚舉+剪枝 ]

來源:互聯網
上載者:User

   主要思想就是:先排序(按行號升序,若行號相等就按列號升序);再枚舉每兩個點,以兩個點分別為青蛙所走路線上的第一個點和第二個點(在枚舉的過程中的剪枝非常重要);

//   枚舉 + 剪枝#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);}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.