题解:P3433 [POI 2005] PRA-Dextrogyrate Camel
Theobaldthebird · · 题解
这个问题可以建模为一个图论问题,需要找到满足特定条件的最长路径。以下是解决方案的思路和实现方法:
问题分析: 我们需要找到一个闭合路径,起点和终点都是Byteasar所在的绿洲 路径必须满足"右转"约束(每次转弯必须是顺时针方向且角度在0-180度之间) 路径不能自相交(除了起点/终点) 初始方向固定(必须朝向指定的第一个绿洲) 解决方法: 将问题转化为有向图,其中边表示合法的移动(满足转弯约束) 使用动态规划来记录状态:dp[u][v]表示最后两个访问点是u→v时的最大路径长度 状态转移时,检查新加入的点w是否满足从u→v→w是合法的右转 算法实现: 预处理所有点对之间的角度关系 初始化从起点到初始方向点的路径 逐步扩展路径,确保每次转弯合法 最后检查是否能回到起点
include <iostream>
include <vector>
include <algorithm>
include <cmath>
include <map>
using namespace std;
struct Point { int x, y; Point(int x=0, int y=0) : x(x), y(y) {} bool operator==(const Point& other) const { return x == other.x && y == other.y; } };
int cross(const Point& o, const Point& a, const Point& b) { return (a.x-o.x)(b.y-o.y) - (a.y-o.y)(b.x-o.x); }
int main() { int N; cin >> N; vector<Point> points(N); for (int i = 0; i < N; ++i) { cin >> points[i].x >> points[i].y; }
Point start = points[0];
Point initial_dir = points[1];
vector<Point> other_points;
for (const auto& p : points) {
if (!(p == start) && !(p == initial_dir)) {
other_points.push_back(p);
}
}
// DP state: last two points in path -> max length
map<pair<Point, Point>, int> dp;
dp[{start, initial_dir}] = 1;
int max_len = 0;
for (int step = 0; step < N-1; ++step) {
map<pair<Point, Point>, int> new_dp;
for (const auto& [key, len] : dp) {
const Point& u = key.first;
const Point& v = key.second;
Point last_vec = {v.x - u.x, v.y - u.y};
for (const Point& w : other_points) {
if (w == u || w == v) continue;
Point new_vec = {w.x - v.x, w.y - v.y};
int cross_prod = last_vec.x * new_vec.y - last_vec.y * new_vec.x;
if (cross_prod <= 0) { // Right turn or straight
auto new_key = make_pair(v, w);
if (new_dp.count(new_key)) {
if (len + 1 > new_dp[new_key]) {
new_dp[new_key] = len + 1;
}
} else {
new_dp[new_key] = len + 1;
}
}
}
}
if (new_dp.empty()) break;
dp = new_dp;
// Check if we can return to start
for (const auto& [key, len] : dp) {
const Point& u = key.first;
const Point& v = key.second;
Point last_vec = {v.x - u.x, v.y - u.y};
Point return_vec = {start.x - v.x, start.y - v.y};
int cross_prod = last_vec.x * return_vec.y - last_vec.y * return_vec.x;
if (cross_prod <= 0) {
if (len + 1 > max_len) {
max_len = len + 1;
}
}
}
}
cout << max_len << endl;
return 0;
}