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

这道题目非常的好,个人非常的喜欢!

这道题目的意思是:两个人要坐火车相遇到一个城市,但是坐火车到一个城市的时间是不确定的,第一个人到车站的时间范围是[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;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值