您的位置:首页 > 其它

《算法竞赛-训练指南》第二章-2.15_UVa 11722

2013-08-16 20:39 253 查看
这道题目非常的好,个人非常的喜欢!

这道题目的意思是:两个人要坐火车相遇到一个城市,但是坐火车到一个城市的时间是不确定的,第一个人到车站的时间范围是[t1,t2],第二个人到车站的时间范围是[s1,s2],而车在车站停留的时间是w。问你两人在车站相遇的概率是多少?

其实我认为这道题目的结果是有些问题的,其实题解是按照[t1,t2]范围内,火车已经离开的,但是按照真实的题意,不应该t2到,t2 + w火车才走么?所有有些问题,不过我们主要是学个思路!

题解又以惊人的代码征服了我,代码精短,而且效率,分类解题的能力跃然纸上,这就是为什么脑子好的人,就是真正越到了困难也能化险为夷,因为他们的思想非常的理性,解决问题的步骤早就想好了。

题解的分类非常的好,这个看了都能明白,但是自己想,估计就很难了,这就是聪明与不聪明,题目做的多和做的少的区别,贴出代码:

#include <stdio.h>
#include <string.h>
#include <iostream>
#include <string>

using namespace std;

double t1, t2, s1, s2, w;

double height, width;

double getArea(double W)
{
double tx = s2 - W;
double bx = s1 - W;
double ly = t1 + W;
double ry = t2 + W;
bool onLeft = (ly <= s2 && ly >= s1);
bool onRight = (ry <= s2 && ry >= s1);
bool onTop = (tx <= t2 && tx >= t1);
bool onBottom = (bx <= t2 && bx >= t1);
if (onLeft && onTop)
{
return (tx - t1) * (s2 - ly) * 0.5;
}
if (onLeft && onRight)
{
return ((tx - t1) * (s2 - ly) - (tx - t2) * (s2 - ry)) * 0.5;
// return (s2 - ly + s2 - ry) * width * 0.5;
}
if (onTop && onBottom)
{
return ((tx - t1) * (s2 - ly) - (s1 - ly) * (bx - t1)) * 0.5;
// return (bx - t1 + tx - t1) * height * 0.5;
}
if (onBottom && onRight)
{
return (height * width) - (t2 - bx) * (ry - s1) * 0.5;
}
return ly <= s1 ? height * width : 0;
}

int main()
{
int T;
scanf("%d", &T);
for (int Case = 1; Case <= T; Case++)
{
scanf("%lf%lf%lf%lf%lf", &t1, &t2, &s1, &s2, &w);
width = (t2 - t1);
height = (s2 - s1);
double ans1 = getArea(w);
double ans2 = getArea(-1 * w);
// cout << ans2 << endl;
// cout << ans1 << endl;
printf("Case #%d: %.8lf\n", Case, (ans2 - ans1) / (width * height));
}
// system("pause");
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: