高中也做个这种类似的题目,概率空间是[t1, t2] × [s1, s2]的矩形,设x、y分别代表两辆列车到达的时间,则两人相遇的条件就是|x - y| <= w
从图形上看就是矩形夹在两条平行线之间的部分。
因为情况众多,一个一个分类很麻烦,而且可能有漏掉情况,所以就用计算几何的办法求了个凸多边形,多边形 与 矩形面积之比就是概率。
代码有点挫,将就看,=_=||
#include <cstdio>
#include <vector>
#include <cmath>
using namespace std; struct Point
{
double x, y;
Point(double x=, double y=):x(x), y(y) {}
};
typedef Point Vector;
typedef vector<Point> Polygon; Point operator + (const Point& A, const Point& B)
{ return Point(A.x+B.x, A.y+B.y); } Vector operator - (const Point& A, const Point& B)
{ return Point(A.x-B.x, A.y-B.y); } Vector operator * (const Vector& A, double p)
{ return Vector(A.x*p, A.y*p); } double Cross(const Vector& A, const Vector& B)
{ return A.x * B.y - A.y * B.x; } double PolygonArea(const Polygon& p)
{//求多边形面积
int n = p.size();
double area = ;
for(int i = ; i < n-; i++)
area += Cross(p[i]-p[], p[i+]-p[]);
return area/;
} Point Intersection(Point P, Vector v, Point Q, Vector w)
{//求两直线交点
Vector u = P-Q;
double t = Cross(w, u) / Cross(v, w);
return P+v*t;
} const double sqrt2 = sqrt(2.0);
const Vector v1(, ), v2(, ), v3(, );
double t1, t2, s1, s2, w;
Polygon poly; bool in(const Point& p)
{ return p.x >= t1 && p.x <= t2 && p.y >= s1 && p.y <= s2; } void check(Point p)
{
if(in(p) && fabs(p.x-p.y) <= w)//该点要在矩形内两平行线之间
poly.push_back(Point(p.x, p.y));
} int main()
{
//freopen("in.txt", "r", stdin); int T;
scanf("%d", &T);
for(int kase = ; kase <= T; kase++)
{
poly.clear();
scanf("%lf%lf%lf%lf%lf", &t1, &t2, &s1, &s2, &w);
Point p(t1, s2), p1(, w), p2(, -w);
check(p);
p = Intersection(Point(t1, ), v2, p1, v3); check(p);
p = Intersection(Point(t1, ), v2, p2, v3); check(p);
p = Point(t1, s1); check(p);
p = Intersection(Point(, s1), v1, p1, v3); check(p);
p = Intersection(Point(, s1), v1, p2, v3); check(p);
p = Point(t2, s1); check(p);
p = Intersection(Point(t2, ), v2, p2, v3); check(p);
p = Intersection(Point(t2, ), v2, p1, v3); check(p);
p = Point(t2, s2); check(p);
p = Intersection(Point(, s2), v1, p2, v3); check(p);
p = Intersection(Point(, s2), v1, p1, v3); check(p);
//for(int i = 0; i < poly.size(); i++) printf("%.3f %.3f\n", poly[i].x, poly[i].y);
double A = PolygonArea(poly);
double B = (t2-t1) * (s2-s1);
double ans = A / B;
printf("Case #%d: %.8f\n", kase, ans);
} return ;
}
代码君