题意:求从正方体外面到达这个黑点所需穿过的最少线段数(规定只能从线段中点穿过,包括最外层的墙),共有n面墙
0 <= n <= 30
题解:事实上枚举边界上的中点,判断它和黑点的线段与这些墙的交点数即可
解释:注意到,墙这一长线段相对于黑点连线,等价于直线——无论是在实现上还是题意上。连线若与墙相交,则黑点与枚举点必在墙两侧,无可避免地要穿过这面墙,至于从线段中点穿过在本题中是没有意义的。起始点选取本该在线段中点,但显然选取两个端点的最小值不会比它差,而一个端点的结果不会比相邻的两个中点结果好,所以枚举端点即可。
实现注意点:判断时用line_cross_segment即可,判断时使用规范相交,记得加上初始穿过边界所需的1次
事实上我的第一想法是枚举出所有线段的中点,再用相交判断合法边,用一次bfs搜出最短路,显然麻烦又没有好好利用题目性质,但暂且先写下这个思路。
#include<cmath> #include<cstdio> #include<cstring> #include<algorithm> using namespace std; #define rep(i,a,b) for (int i=a;i<=b;++i) const double eps=1e-7; struct point{ double x,y; point(){} point (double a,double b): x(a),y(b) {} friend point operator + (const point &a,const point &b){ return point(a.x+b.x,a.y+b.y); } friend point operator - (const point &a,const point &b){ return point(a.x-b.x,a.y-b.y); } friend point operator * (const double &r,const point &a){ return point(r*a.x,r*a.y); } friend bool operator == (const point &a,const point &b){ return (abs(a.x-b.x)<eps && abs(a.y-b.y)<eps); } double norm(){ return sqrt(x*x+y*y); } }; inline double det(point a,point b) {return a.x*b.y-a.y*b.x;} inline bool line_cross_segment(point s,point t,point a,point b) { return det(s-a,t-a)*det(s-b,t-b)<-eps; } int n,tot,x,y; point s[50],t[50],goal; int ans,temp; int check(point a,point b) { int temp=0; rep(i,1,n) if (line_cross_segment(s[i],t[i],a,b)) ++temp; return temp; } int main() { scanf("%d",&n); rep(i,1,n) scanf("%lf%lf%lf%lf",&s[i].x,&s[i].y,&t[i].x,&t[i].y); ans=100000; scanf("%lf%lf",&goal.x,&goal.y); rep(i,1,n) { ans=min(ans,check(s[i],goal)); ans=min(ans,check(t[i],goal)); } if (n==0) ans=0; printf("Number of doors = %d ",ans+1); return 0; }