Clock
Time Limit: 2000/1000 MS (Java/Others)
Memory Limit: 65536/32768 K (Java/Others)
Problem Description
There is an analog clock with two hands: an hour hand and a minute hand. The two hands form an angle. The angle is measured as the smallest angle between the two hands. The angle between the two hands has a measure that is greater than or equal to 0 and less than or equal to 180 degrees.
Given a sequence of five distinct times written in the format hh : mm , where hh are two digits representing full hours (00 <= hh <= 23) and mm are two digits representing minutes (00 <= mm <= 59) , you are to write a program that finds the median, that is, the third element of the sorted sequence of times in a nondecreasing order of their associated angles. Ties are broken in such a way that an earlier time precedes a later time.
For example, suppose you are given a sequence (06:05, 07:10, 03:00, 21:00, 12:55) of times. Because the sorted sequence is (12:55, 03:00, 21:00, 06:05, 07:10), you are to report 21:00.
Input
The input consists of T test cases. The number of test cases (T) is given on the first line of the input file. Each test case is given on a single line, which contains a sequence of five distinct times, where times are given in the format hh : mm and are separated by a single space.
Output
Print exactly one line for each test case. The line is to contain the median in the format hh : mm of the times given. The following shows sample input and output for three test cases.
Sample Input
3
00:00 01:00 02:00 03:00 04:00
06:05 07:10 03:00 21:00 12:55
11:05 12:05 13:05 14:05 15:05
Sample Output
02:00
21:00
14:05
思路:
对clock结构体进行排序,计算出时针和分针的夹角度数即可
(1)时针每走一个小时,转动360/12=30度,即(hh%12)*30度;
(2) 时针每走一分钟,转动360/(12*60)=0.5度,即mm*0.5度;
所以,时针角度为(hh%12)*30+mm*0.5度。
(3)分针每走一分钟,转动360/60=6度,即mm*6度;
所以,分针角度为mm*6度。
(4)两者相减,再与180比较,若大于180,则用360减去度数,若不大于,即可进行排序。
注意:输出时要用printf,否则14:05会变成14:5。
AC代码:
#include <iostream>
#include <algorithm>
#include <cmath>
#include <stdio.h>
using namespace std;
struct clock{
int hh;
int mm;
double angle;
}time[5];
bool cmp(clock x,clock y)
{
if(x.angle!=y.angle) return x.angle<y.angle;
else if(x.angle==y.angle&&x.hh==y.hh) return x.mm<y.mm;
else return x.hh<y.hh;
}
int main()
{
int t;
char ch=':';
while(cin>>t)
{
for(int i=0;i<t;i++)
{
for(int j=0;j<5;j++)
{
cin>>time[j].hh>>ch>>time[j].mm;
double anglehh=(time[j].hh%12)*30+time[j].mm*0.5;
double anglemm=time[j].mm*6;
time[j].angle=abs(anglehh-anglemm)>180?(360-abs(anglehh-anglemm)):abs(anglehh-anglemm);
}
sort(time,time+5,cmp);
printf("%02d:%02d\n",time[2].hh,time[2].mm);
//cout<<time[2].hh<<ch<<time[2].mm<<endl;
}
}
return 0;
}