Treasure Hunt--POJ 1066

1、题目类型:计算几何、线段相交。

2、解题思路:分析,读题后第一想法是从treasure点多边形向外做BFS直到到达边界,但区域内的各个不规则多边形无法确定;后发现只要在区域的四周的焦点间中点做与treasure点的线段,获取其最小焦点就可(即使线段通过内部线段的交点此时不影响结果,同样计算了两次)。步骤,(1)对区域四个边界上的点进行排序(源码的方法比较呆板、代码比较冗余,应该有更好的方法);(2)对四个边界上,相邻焦点的中点与treasure点做线段并与其他线段判断相交,获得最小交点树的情况,即为此题最优。

3、注意事项:注意计算几何模板的应用,判断线段相交的点是有序的。

4、实现方法:

#include<iostream>
#include
<algorithm>
using namespace std;
const double eps=1e-10;

struct point
{
double x, y;
};

struct Tline
{
point p1,p2;
};

point side[
4][35],End;
Tline line[
31];
int num[4],ans,n;

double min(double a, double b) { return a < b ? a : b; }
double max(double a, double b) { return a > b ? a : b; }

bool inter(point a, point b, point c, point d)
{
if ( min(a.x, b.x) > max(c.x, d.x) ||
min(a.y, b.y)
> max(c.y, d.y) ||
min(c.x, d.x)
> max(a.x, b.x) ||
min(c.y, d.y)
> max(a.y, b.y) )
return 0;
double h, i, j, k;
h
= (b.x - a.x) * (c.y - a.y) - (b.y - a.y) * (c.x - a.x);
i
= (b.x - a.x) * (d.y - a.y) - (b.y - a.y) * (d.x - a.x);
j
= (d.x - c.x) * (a.y - c.y) - (d.y - c.y) * (a.x - c.x);
k
= (d.x - c.x) * (b.y - c.y) - (d.y - c.y) * (b.x - c.x);
return h * i <= eps && j * k <= eps;
}

bool cmp(point p1,point p2)
{
return (p1.y==p2.y && p1.x<p2.x)||(p1.x==p2.x && p1.y<p2.y);
}

void Solve()
{
int i,j;
memset(num,
0,sizeof(num));
for(i=0;i<n;i++)
{
if(line[i].p1.x==0){
side[
0][num[0]].x=0;
side[
0][num[0]].y=line[i].p1.y;
num[
0]++;}
if(line[i].p2.x==0){
side[
0][num[0]].x=0;
side[
0][num[0]].y=line[i].p2.y;
num[
0]++;}

if(line[i].p1.x==100){
side[
1][num[1]].x=100;
side[
1][num[1]].y=line[i].p1.y;
num[
1]++;}
if(line[i].p2.x==100){
side[
1][num[1]].x=100;
side[
1][num[1]].y=line[i].p2.y;
num[
1]++;}

if(line[i].p1.y==0){
side[
2][num[2]].x=line[i].p1.x;
side[
2][num[2]].y=0;
num[
2]++;}
if(line[i].p2.y==0){
side[
2][num[2]].x=line[i].p2.x;
side[
2][num[2]].y=0;
num[
2]++;}

if(line[i].p1.y==100){
side[
3][num[3]].x=line[i].p1.x;
side[
3][num[3]].y=100;
num[
3]++;}
if(line[i].p2.y==100){
side[
3][num[3]].x=line[i].p2.x;
side[
3][num[3]].y=100;
num[
3]++;}
}
side[
0][num[0]].x=0;
side[
0][num[0]].y=100;
side[
1][num[1]].x=100;
side[
1][num[1]].y=100;
side[
2][num[2]].x=100;
side[
2][num[2]].y=0;
side[
3][num[3]].x=100;
side[
3][num[3]].y=100;

for(i=0;i<4;i++)
sort(side[i],side[i]
+num[i],cmp);
point p,q,mid;
int m,k;
for(i=0;i<4;i++)
{
p.x
=0;
p.y
=0;
for(j=0;j<=num[i];j++)
{
m
=1;
q
=side[i][j];
mid.x
=(q.x+p.x)*0.5;
mid.y
=(q.y+p.y)*0.5;
for(k=0;k<n;k++)
if(inter(mid,End,line[k].p1,line[k].p2))
m
++;
if(m<ans)
ans
=m;
p
=q;
}
}
}

int main()
{
int i;
memset(side,
0,sizeof(side));
scanf(
"%d",&n);
for(i=0;i<n;i++)
{
scanf(
"%lf%lf%lf%lf",&line[i].p1.x,&line[i].p1.y,&line[i].p2.x,&line[i].p2.y);
}
scanf(
"%lf%lf",&End.x,&End.y);
ans
=99999;
Solve();
cout
<<"Number of doors = "<<ans<<endl;
return 0;
}

 

posted @ 2010-09-24 15:47  勇泽  阅读(427)  评论(0编辑  收藏  举报