uva11722(概率)

題意:

兩個人到達車站的時間分別是t1-t2, s1-s2;並且到站後停留w分鐘.問相遇的概率;


思路:

高中數學學過這個問題;首先是x軸取t1, t2,y軸取s1,s2畫四條線,圍出的矩形就是全集,即所有可能行;

然後兩個人要相遇,則到站時間只能相差w以內;

所以畫兩條直線y = x + w ; y = x - 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;
	}
	if (onTop && onBottom) {
		return ((tx - t1) * (s2 - ly) - (s1 - ly) * (bx - t1)) * 0.5;
	}
	if (onBottom && onRight) {
		return (height * width) - (t2 - bx) * (ry - s1) * 0.5;
	}
	return ly <= s1 ? height * width : 0;
}
	

int main() {
	int t;
	int cas = 1;
	scanf("%d", &t);
	while (t--) {
		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);
		printf("Case #%d: %.8lf\n", cas++, (ans2 - ans1) / (width * height));
	}
	return 0;
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章