题目链接:http://poj.org/problem?id=1066
题意:
7
20 0 37 100
40 0 76 100
85 0 0 75
100 90 0 90
0 71 100 61
0 14 100 38
100 47 47 100
54.5 55.4
7堵墙,最后一行为宝藏的坐标。
给出一个100*100的正方形区域,通过若干连接区域边界的线段将正方形区域分割为多个不规则多边形小区域,然后给出宝藏位置,要求从区域外部开辟到宝藏所在位置的一条路径,使得开辟路径所需要打通的墙壁数最少("打通一堵墙"即在墙壁所在线段中间位置开一空间以连通外界),输出应打通墙壁的个数(包括边界上墙壁)。
因为所有墙的坐标都是整数,所以本来想枚举所有的入口,后来发现只需要枚举所有墙的端点就可以了,因为那就包括了所有的可能。注意枚举端点时结果多加了一个1,而打破外围墙时正好需要加一,所以直接输出答案即可。注意特判0。
#include <iostream>
#include <cstdio>
#include <cstring>
#include <algorithm>
#include <vector>
#include <queue>
#include <cmath>
using namespace std;
const double eps = 1e-8;
const double PI = acos(-1.0);
int sgn(double x) {
if(fabs(x) < eps)return 0;
if(x < 0)return -1;
else return 1;
}
struct Point {
double x,y;
Point(){}
Point(double _x,double _y) {
x = _x;y = _y;
}
Point operator -(const Point &b)const {
return Point(x - b.x,y - b.y);
}
double operator ^(const Point &b)const {
return x*b.y - y*b.x;
}
double operator *(const Point &b)const {
return x*b.x + y*b.y;
}
void transXY(double B) {
double tx = x,ty = y;
x = tx*cos(B) - ty*sin(B);
y = tx*sin(B) + ty*cos(B);
}
};
struct Line {
Point s,e;
Line(){}
Line(Point _s,Point _e) {
s = _s;e = _e;
}
pair<int,Point> operator &(const Line &b)const {
Point res = s;
if(sgn((s-e)^(b.s-b.e)) == 0) {
if(sgn((s-b.e)^(b.s-b.e)) == 0) return make_pair(0,res);
else return make_pair(1,res);
}
double t = ((s-b.s)^(b.s-b.e))/((s-e)^(b.s-b.e));
res.x += (e.x-s.x)*t;
res.y += (e.y-s.y)*t;
return make_pair(2,res);
}
};
double dist(Point a,Point b) {
return sqrt((a-b)*(a-b));
}
bool inter(Line l1,Line l2) { //判断线段相交
return
max(l1.s.x,l1.e.x) >= min(l2.s.x,l2.e.x) &&
max(l2.s.x,l2.e.x) >= min(l1.s.x,l1.e.x) &&
max(l1.s.y,l1.e.y) >= min(l2.s.y,l2.e.y) &&
max(l2.s.y,l2.e.y) >= min(l1.s.y,l1.e.y) &&
sgn((l2.s-l1.e)^(l1.s-l1.e))*sgn((l2.e-l1.e)^(l1.s-l1.e)) <= 0 &&
sgn((l1.s-l2.e)^(l2.s-l2.e))*sgn((l1.e-l2.e)^(l2.s-l2.e)) <= 0;
}
vector<Line> li;
int main() {
int n;
scanf("%d", &n);
double sx, sy, ex, ey;
int i, j;
for(i = 0; i < n; i++) {
scanf("%lf %lf %lf %lf", &sx, &sy, &ex, &ey);
Point s(sx, sy), e(ex, ey);
li.push_back(Line(s, e));
}
scanf("%lf %lf", &ex, &ey);
if(n == 0) {
printf("Number of doors = 1\n");
return 0;
}
Point e(ex, ey);
int ans = 1000;
for(i = 0; i < li.size(); i++) { //枚举所有的入口
Line t1(li[i].s, e), t2(li[i].e, e);
int cnt1 = 0, cnt2 = 0;
for(j = 0; j < li.size(); j++) {
if(inter(t1, li[j])) cnt1++;
if(inter(t2, li[j])) cnt2++;
}
if(ans > cnt1) ans = cnt1;
if(ans > cnt2) ans = cnt2;
}
printf("Number of doors = %d\n", ans);
return 0;
}