Problem I: Catching Dogs
Time Limit: 1 Sec Memory Limit: 128 MBSubmit: 1109 Solved: 288
[ Submit][ Status][ Web Board]
Description
Diao Yang keeps many dogs. But today his dogs all run away. Diao Yang has to catch them. To simplify the problem, we assume Diao Yang and all the dogs are on a number axis. The dogs are numbered from 1 to n. At first Diao Yang is on the original point and his speed is v. The ith dog is on the point ai and its speed is vi . Diao Yang will catch the dog by the order of their numbers. Which means only if Diao Yang has caught the ith dog, he can start to catch the (i+1)th dog, and immediately. Note that When Diao Yang catching a dog, he will run toward the dog and he will never stop or change his direction until he has caught the dog. Now Diao Yang wants to know how long it takes for him to catch all the dogs.
Input
There are multiple test cases. In each test case, the first line contains two positive integers n(n≤10) andv(1≤v≤10). Then n lines followed, each line contains two integers ai(|ai|≤50) and vi(|vi|≤5). vi<0 means the dog runs toward left and vi>0 means the dog runs toward right. The input will end by EOF.
Output
For each test case, output the answer. The answer should be rounded to 2 digits after decimal point. If Diao Yang cannot catch all the dogs, output “Bad Dog”(without quotes).
Sample Input
2 5
-2 -3
2 3
1 6
2 -2
1 1
0 -1
1 1
-1 -1
Sample Output
6.00
0.25
0.00
Bad Dog
HINT
注意用double类型不要用float,后者通不过,精度不够!
#include<stdio.h>
#include<string.h>
#include<math.h>
int main()
{
int n,v,i,j;
int flag=0;
int dogv[14];//狗速度
double pos;//人的位置
double t,t1;//时间。t1代表追上一条狗的时间
double dogp[14];//狗的位置
while(scanf("%d %d",&n,&v)!=EOF)
{
flag=0;
memset(dogp,0,sizeof(dogp));
memset(dogv,0,sizeof(dogv));
pos=0;
t=0;
for(i=1;i<=n;i++)
{
scanf("%lf %d",&dogp[i],&dogv[i]);
}
for(i=1;i<=n;i++)
{
if(pos>dogp[i])//人在右边
{
if(dogv[i]<0)//狗远离人方向
{
if(abs(dogv[i])>=v)//相反方向,狗大于人的速度
{
printf("Bad Dog\n");
flag=1;
break;
}
else//计算出时间
{
t1=(double)(pos-dogp[i])/(double)(v+dogv[i]);
pos-=v*t1;
}
}
else //相向而行
{
t1=(double)(pos-dogp[i])/(double)(v+dogv[i]);
pos-=v*t1;
}
}
else if(pos<dogp[i])//人在左边
{
if(dogv[i]>0)
{
if(dogv[i]>=v)
{
printf("Bad Dog\n");
flag=1;
break;
}
else
{
t1=(double)(dogp[i]-pos)/(double)(v-dogv[i]);
pos+=v*t1;
}
}
else
{
t1=(double)(dogp[i]-pos)/(double)(v-dogv[i]);
pos+=v*t1;
}
}
else //在同样的位置
t1=0;
t+=t1;
for(j=i;j<=n;j++)//更新其他狗的位置
{
dogp[j]=dogv[j]*t1+dogp[j];
}
}
if(!flag) printf("%.2lf\n",t);
}
return 0;
}