POJ 1852 Ants 简单的弹性碰撞问题简单的弹性碰撞问题
题目传送门 点击这里
中文大意:中文大意:
有n只蚂蚁在木棍上爬行,每只蚂蚁的速度都是每秒1单位长度,现在给出所有蚂蚁初始的位置,但是没有给出蚂蚁的运动方
向,如果蚂蚁相遇会掉头反向运动,需要求出所有蚂蚁都·掉下木棍的最短时间和最长时间。
解题思路概要解题思路概要:
两个蚂蚁相撞之后,其实跟没有撞的效果是一样的。相当于还是每个蚂蚁在单独运动。
所以准备了两个数组,第一个数组存放题目中录入的数据。
第二个数组的大小是第一个数组的二倍。其中存入的数据除了第一个数组中的数据外,还要有木棍的长度减去第一个数组中的
每个数。
相当于说第二个数组中存放的是每个蚂蚁到左右两个端点的距离。
然后用快排对第二个数组进行排序。
其中下标为num-1的恰好是最短时间,下标为num*2-1的恰好为最长的时间。
源代码及注释见下源代码及注释见下
//written by Kingdeguo 2020.4.4
//All rights reversed
#include
#include //to use qsort
//declare out of main function because is the scale of data is a little big
//prevent stack overflow
const int maxn = 1000010;
int Distance[maxn];
int Distance2[maxn*2];
int cmp(const void *a,const void *b)
{
return *(int *)a-*(int *)b;//If you want to from large to small,write this "return *(int *)b-*(int *)a;"
}
int main()
{
int casenum=0;
int length=0, num=0;
scanf("%d",&casenum);
int i=0;
while(casenum){
scanf("%d %d",&length,&num);
for(i=0; i<num; ++i){
scanf("%d",&Distance[i]);
Distance2[i]=Distance[i];
Distance2[i+num] = length-Distance[i];
}
qsort(Distance2,num*2,sizeof(Distance2[0]),cmp);
printf("%d %d",Distance2[num-1],Distance2[num*2-1]);
casenum--;
}
return 0;
}
作者:Kingdeguo
评论0