枚举

题目描述
题目链接:http://bailian.openjudge.cn/practice/2812/
解题思路
因为要求出最长路径,所以需要比较全部的路径长度,对于每一条路径,因为步长相等,所以只需要确定开始两个被踩的点就可以确定整条路径,一条合法的路径要满足这些条件:
1.初始点向前走一个步长在地图之外。
2.末尾点后一个点在图外
3.从开始点向后依次推步长,每个点一定是图上被踩过的点。

求解这个问题的时候可以做一些优化:
1.如果第一个点前一个点没在图外,当前枚举的两个点不满足条件
2.如果第一个点经过已经找到的最常路径跳到了图外,那么即使这个对点满足条件,也不会比之前结果更好,可以直接跳过。

解题代码

#include <cstdio>
#include <cstring>
#include <algorithm>

using namespace std;

struct Point {
    int x, y;
}p[6000];
int flags[6000][6000];
void count(int , int );
bool outside(int, int);


int r, c, n;
int ans;

bool operator < (const Point & a, const Point & b){
    return (a.x < b.x || (a.x == b.x && a.y < b.y));
}

void count(int a, int b){ //判断以a和b为起点的路径是否存在
    int dx = p[b].x - p[a].x;
    int dy = p[b].y - p[a].y;
    if(!outside(p[a].x - dx, p[a].y - dy)) return;
    if(outside(p[a].x + ans * dx, p[a].y + ans * dy)) return;
    
    int k = 2;
    int x1 = p[b].x + dx;
    int y1 = p[b].y + dy;
    while(!outside(x1, y1) && flags[x1][y1])
    {
        k++;
        x1 += dx;
        y1 += dy;
    }
    if(outside(x1, y1) && k > ans) ans = k;
 
}

bool outside(int x , int y){
    if(x <= 0 || x > r || y <= 0 || y > c) return true;
    else return false;
}

int main(){
    scanf("%d%d%d", &r, &c, &n);
    for(int i = 0; i < n; i++){
        scanf("%d%d", &p[i].x, &p[i].y);
        flags[p[i].x][p[i].y] = 1;
    }
    sort(p, p + n);
    for(int i = 0; i < n - 1; i++)
        for(int j = i + 1; j < n; j++)
            count(i, j);
    if(ans < 3) ans = 0;
    printf("%d
", ans);
    return 0;
}
原文地址:https://www.cnblogs.com/zhangyue123/p/12705208.html