题目不难,注意几个点:
- 绿灯、黄灯、红灯时间都是整型;
- 速度为整型,范围为 [30, 60];
- 绿灯和黄灯都可以通过;
- 注意输出格式。
#include <iostream>
using namespace std;
struct signal //信号灯
{
double dis; //距停车场的距离(英里)
int cycle; //信号灯周期(秒)
int go; //每个信号灯周期中能通过的时间(秒)
}s[10];
int main()
{
int Case = 1; //测试用例数
int N;
while (cin >> N)
{
if (N == -1)
break;
int g, y, r; //绿灯时间,黄灯时间,红灯时间
for (int i = 0; i < N; i++)
{
cin >> s[i].dis >> g >> y >> r;
s[i].cycle = g + y + r;
s[i].go = g + y;
}
int speed[35]; //满足要求的速度
int index = 0;
double time; //到达当前信号灯的时间(秒)
bool flag; //到达每个信号灯时,是否都是绿灯或黄灯
for (int v = 30; v <= 60; v++) //判断每个速度是否满足要求
{
flag = true;
for (int i = 0; i < N; i++) //依次判断每个信号灯
{
time = s[i].dis * 3600 / v;
time -= (int)time / s[i].cycle * s[i].cycle;
if (time > s[i].go)
{
flag = false;
break;
}
}
if (flag) //当前速度满足要求
speed[index++] = v;
}
cout << "Case " << Case++ << ": ";
if (index > 0) //输出
{
int i, j;
for (i = 0; i < index - 1; i++)
{
cout << speed[i];
int total = 0; //能够和speed[i]组合的速度的数量
for (j = i + 1; j < index; j++)
{
if (speed[j] == speed[j - 1] + 1)
++total;
else
break;
}
if (total > 0)
{
cout << "-";
if (j < index)
cout << speed[j - 1] << ", ";
i = j - 1;
}
else
cout << ", ";
}
cout << speed[index - 1] << endl;
}
else
cout << "No acceptable speeds." << endl;
}
return 0;
}
继续加油。