A Curious Matt
There is a curious man called Matt.
One day, Matt's best friend Ted is wandering on the non-negative half of the number line. Matt finds it interesting to know the maximal speed Ted may reach. In order to do so, Matt takes records of Ted’s position. Now Matt has a great deal of records. Please help him to find out the maximal speed Ted may reach, assuming Ted moves with a constant speed between two consecutive records.
InputThe first line contains only one integer T, which indicates the number of test cases.
For each test case, the first line contains an integer N (2 ≤ N ≤ 10000),indicating the number of records.
Each of the following N lines contains two integers t i and x i (0 ≤ t i, x i ≤ 106), indicating the time when this record is taken and Ted’s corresponding position. Note that records may be unsorted by time. It’s guaranteed that all t i would be distinct. OutputFor each test case, output a single line “Case #x: y”, where x is the case number (starting from 1), and y is the maximal speed Ted may reach. The result should be rounded to two decimal places.
Sample Input
2 3 2 2 1 1 3 4 3 0 3 1 5 2 0
Sample Output
Case #1: 2.00 Case #2: 5.00
Hint
In the first sample, Ted moves from 2 to 4 in 1 time unit. The speed 2/1 is maximal. In the second sample, Ted moves from 5 to 0 in 1 time unit. The speed 5/1 is maximal.
题意:
这道题的意思是输入某个时间和位置,然后所要求的就是在某一秒内的速度最大值。但是时间大小不一定就是按照时间顺序排列好的。
思路:
我们先看一下这一道题的数据范围N是0~10000的,ti和xi都是0~106的,所以用暴力做问题也不大,构建一个结构体分别表示时间和位置的关系,然后再按照时间排序一下位置也就跟着动了,然后逐项求比较大小就行了。
代码:
#include<bits/stdc++.h>
using namespace std;
int t,n;//t表示测试组数
struct node//定义一个结构体方便下面的排序
{
int ti;
int xi;
}a[10001];
int cmp(struct node x,struct node y)//结构体定义时间和位置比较大小的思路
{
return x.ti<y.ti;
}
int main()
{
scanf("%d",&t);//输入测试用例的个数
for(int j=0;j<t;j++)
{
scanf("%d",&n);//输入每个测试用例中的数的个数
for(int i=0;i<n;i++)
{
scanf("%d%d",&a[i].ti,&a[i].xi);//输入每一个数
}
sort(a,a+n,cmp);//将结构体中的数据按照先后的时间顺序进行排序
double maxn=0.00;//用来记录最大的速度
for(int i=0;i<n-1;i++)//逐一进行比较
{
if((double)(abs(a[i+1].xi-a[i].xi)/(a[i+1].ti-a[i].ti))>maxn)//注意好数据类型
{
maxn=(double)abs(a[i+1].xi-a[i].xi)/abs(a[i+1].ti-a[i].ti);
}
}
printf("Case #%d: ",j+1);
printf("%.2lf\n",maxn);
}
return 0;
}