Problem Description
The three hands of the clock are rotating every second and meeting each other many times everyday. Finally, they get bored of this and each of them would like to stay away from the other two. A hand is happy if it is at least D degrees from any of the rest. You are to calculate how much time in a day that all the hands are happy.
Input
The input contains many test cases. Each of them has a single line with a real number D between 0 and 120, inclusively. The input is terminated with a D of -1.
Output
For each D, print in a single line the percentage of time in a day that all of the hands are happy, accurate up to 3 decimal places.
Sample Input
0
120
90
-1
Sample Output
100.000
0.000
6.251
题意就是找钟表的三个指针两两之间的角度超过n的概率。
我一开始想直接暴力,感觉肯定会超时,就查看了大佬的思路,感觉不是太难,就是有点麻烦。
解题思路:将一天的时间24小时只求12小时即可,因为后12小时和前12小时每种情况出现的概率一样,找出三个指针的相对角度:hm、hs、ms。以及时间thm、ths、tms。我们可以求出从重合到分离n度所需的时间n/hm,n/hs,n/ms,以及到再重合前n度所需的时间(360-n)/hm,(360-n)/hs,(360-n)/ms。每次枚举,i,j,k表示hm,hs,ms各自重合的时间,那么p=max(i+n/hm,j+n/hs,k+ms)就是最早的三针分离n度的时间;q=min(i+(360-n)/hm,j+(360-n)/hs,k+(360-n)/ms)就是最晚三针合并到n度的时间,那么时间区间[p,q]就是符合条件的时间段。
#include<iostream>
#include<stdio.h>
#include<algorithm>
#include<iomanip>
using namespace std;
int maxhalf=43200;
double hm,hs,ms,T_hm,T_hs,T_ms;
void speed()
{
double h,m,s;
h=30.0/3600; //时针的速度
m=360.0/3600; //分针的速度
s=360.0/60; //秒针的速度
hm=m-h; //速度差
hs=s-h;
ms=s-m;
T_hm=360/hm;
T_hs=360/hs;
T_ms=360/ms;
}
double maximum(double a,double b,double c) //求最大值
{
return max(max(a,b),c);
}
double minmum(double a,double b,double c) //求最小值
{
return min(min(a,b),c);
}
int main()
{
speed();
double n;
while(scanf("%lf",&n)&&n!=-1)
{
double a[6],i,j,k,begintime,endtime,result=0;
a[0]=n/hm;
a[1]=n/hs;
a[2]=n/ms;
a[3]=(360-n)/hm;
a[4]=(360-n)/hs;
a[5]=(360-n)/ms;
for(i=0;i<=1.0*maxhalf;i+=T_hm)
{
for(j=0;j<=1.0*maxhalf;j+=T_hs)
{
if(j+a[1]>i+a[3]) break;
if(i+a[0]>j+a[4]) continue;
for(k=0;k<=1.0*maxhalf;k+=T_ms)
{
if(k+a[2]>i+a[3]||k+a[2]>j+a[4]) break;
if(i+a[0]>k+a[5]||j+a[1]>k+a[5]) continue;
begintime=maximum(i+a[0],j+a[1],k+a[2]);
endtime=minmum(i+a[3],j+a[4],k+a[5]);
if(endtime>begintime)
result+=(endtime-begintime);
}
}
}
printf("%.3lf\n",result/432);
}
}