链接:http://acm.hust.edu.cn/vjudge/problem/31471
题意:你和你的朋友的火车分别在t1到t2,s1到s2的任意时刻到站,到站停w时间。问能遇上对方的概率是多少?
解析:高中几何概形。求两条线之间的面积。注意:转化为上面那条线之下的面积,减去下面一条线之下的面积
这样就只需讨论矩形和一条线之间的关系,分位六种情况。如图所示:
注意啊:这些线的斜率都是1!!!
图零,此时y2 < s1,线的下方面积为零返回零(以后保证了y2 > s1)
此处另x1 = t1,x2 = t2.y1 = x1 + w,y2 = x2 + w
图一:y1 > s2 返回整个矩形的大小(这就保证了y1 < s2)
图二:y1 >= s1(y2一定大于s1),y2 >= s2。矩形面积减去左边小三角形的面积:x*y - 0.5 * (s2 - y1) ^2.
图三:y1 >= s1,y2 < s2。右侧梯形的面积0.5*(y1 - s1 + y2 - s1) * (x2 - x1)
图四:y1 < s1,y2 <= s2。右下小三角形的面积0.5 *(y2 - s1)^2
图五:y1 < s1,y2 >s2。右侧梯形的面积,首先y = x + w,x = y - w.上底长度为x2 - (s1 - w),下底长度为x2 - (s2 - w).面积为0.5 * (s2 - s1) *(x2 - s1 + w + x2 - s2 + w)//注意加减号
这样六中可能。。。。。。
代码:很简单了,就按照讨论的情况写即可
#include <iostream>
#include <cstdio>
#include <cstring>
#include <sstream>
#include <string>
#include <algorithm>
#include <list>
#include <map>
#include <vector>
#include <queue>
#include <stack>
#include <cmath>
#include <cstdlib>
using namespace std;
int t1,t2,s1,s2;
double fun(int w)
{
int x1 = t1,x2 = t2,y1 = x1 + w,y2 = x2 + w;
int x = x2 - x1;
int y = s2 - s1;
if(y2 <= s1)
return 0;
if(y1 >= s2)
return x * y * 1.0;
if(y1 >= s1)
{
if(y2 >= s2)
return x * y*1.0 - 0.5 * (s2 - y1) * (s2 - y1);
else
return 0.5* (y1- s1 + y2 - s1) * (x2 - x1);
}
else
{
if(y2 <= s2)
return 0.5 * (y2 -s1) * (y2 - s1);
else
return 0.5 * (s2 - s1) *(x2 - s1 + w + x2 - s2 + w);
}
}
int main()
{
//freopen("in.txt","r",stdin);
int T;
scanf("%d",&T);
int w;
for(int t = 1; t <= T; t ++)
{
scanf("%d%d%d%d%d",&t1,&t2,&s1,&s2,&w);
double ans = 0;
double down = (t2 - t1 ) * (s2 - s1) * 1.0;
double up = fun(w) - fun(-w);
ans = up / down;
printf("Case #%d: %.8f\n",t,ans);
}
return 0;
}