Problem B: Ants (弹性碰撞)

来源:互联网 发布:sql unix timestamp 编辑:程序博客网 时间:2024/05/19 13:06
An army of ants walk on a horizontal pole of length l cm, each with a constant speed of 1 cm/s. When a walking ant reaches an end of the pole, it immediatelly falls off it. When two ants meet they turn back and start walking in opposite directions. We know the original positions of ants on the pole, unfortunately, we do not know the directions in which the ants are walking. Your task is to compute the earliest and the latest possible times needed for all ants to fall off the pole.
Input
The first line of input contains one integer giving the number of cases that follow. The data for each case start with two integer numbers: the length of the pole (in cm) and n, the number of ants residing on the pole. These two numbers are followed by n integers giving the position of each ant on the pole as the distance measured from the left end of the pole, in no particular order. All input integers are not bigger than 1000000 and they are separated by whitespace.
Output
For each case of input, output two numbers separated by a single space. The first number is the earliest possible time when all ants fall off the pole (if the directions of their walks are chosen appropriately) and the second number is the latest possible such time.
Sample Input
210 32 6 7214 711 12 7 13 176 23 191
Sample Output
4 838 207

题意:首先一个单独数字表示多少组数据,然后每组数据给出绳子长度,和蚂蚁数,接着每只蚂蚁距离绳头的距离。

蚂蚁爬的规则:每只蚂蚁都能向左或向右爬,每当两只蚂蚁碰头,他们就会都掉头往相反方向爬,请问所有蚂蚁到爬出这根绳子的最短时间和最长时间

思路:蚂蚁碰头其实没有影响的,A向右 B向左 结果碰头了 A向左 B向右 那么就是两只蚂蚁换了个身子继续向前爬而已。

做法:最短时间找出最靠近中间的两只蚂蚁,看看谁更远,将会是最短时间;最长时间就是查最两端的两只蚂蚁,看谁距离另一头更远,那么将是最长时间

代码:
#include<stdio.h>#include<algorithm>#include<string.h>#define MAX 1000005using namespace std;int arr[MAX];int maxx,minn;int L,n;void Find(){    int antmax=-1,antmin=-1;    int i;    for(i=0;i<n;i++){        int maxx=max(arr[i],L-arr[i]);        int minn=min(arr[i],L-arr[i]);        if(maxx>antmax) antmax=maxx;        if(minn>antmin) antmin=minn;    }    printf("%d %d\n",antmin,antmax);}int main(){    int T;    scanf("%d",&T);    while(T--){       scanf("%d%d",&L,&n);       int i;       for(i=0;i<n;i++)            scanf("%d",&arr[i]);       Find();    }return 0;}


原创粉丝点击