当前位置:编程学习 > C/C++ >>

UVA 10714 (13.11.07)

Problem B: Ants
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 anend of the pole, it immediatelly falls off it. When two ants meetthey turn back and start walking in opposite directions. We know theoriginal positions of ants on the pole, unfortunately, we do not knowthe directions in which the ants are walking. Your task is to computethe earliest and the latest possible times needed for all ants to falloff the pole.
The first line of input contains one integer giving the number ofcases that follow. The data for each case start with two integernumbers: the length of the pole (in cm) and n, the number ofants residing on the pole. These two numbers are followed byn integers giving the position of each ant on the pole as thedistance measured from the left end of the pole, in no particularorder. All input integers are not bigger than 1000000 and they areseparated by whitespace.
For each case of input, output two numbers separated by a singlespace. The first number is the earliest possible time when all antsfall off the pole (if the directions of their walks are chosenappropriately) and the second number is the latest possible such time.
Sample input
 
2
10 3
2 6 7
214 7
11 12 7 13 176 23 191
Output for sample input
4 8
38 207
 
题意:首先一个单独数字表示多少组数据,然后每组数据给出绳子长度,和蚂蚁数,接着每只蚂蚁距离绳头的距离。
蚂蚁爬的规则:每只蚂蚁都能向左或向右爬,每当两只蚂蚁碰头,他们就会都掉头往相反方向爬,请问所有蚂蚁到爬出这根绳子的最短时间和最长时间
思路:蚂蚁碰头其实没有影响的,A向右 B向左 结果碰头了 A向左 B向右 那么就是两只蚂蚁换了个身子继续向前爬而已。
做法:最短时间找出最靠近中间的两只蚂蚁,看看谁更远,将会是最短时间;最长时间就是查最两端的两只蚂蚁,看谁距离另一头更远,那么将是最长时间
 
AC代码:
 
#include<stdio.h>  
#include<algorithm>  
  
using namespace std;  
  
int ant[1000005];  
  
int main() {  
    int n;  
    scanf("%d", &n);  
    while(n--) {  
        int l, num;  
        scanf("%d %d", &l, &num);  
        for(int i = 0; i < num; i++)  
            scanf("%d", &ant[i]);  
        int Min, Max;  
        sort(ant, ant+num);  
        Max = max(l - ant[0], ant[num-1]);  
        for(int i = 0; i < num; i++) {  
            if(ant[i] < l / 2)  
                Min = ant[i];  
            else {  
                Min = max(l - ant[i], Min);  
                break;  
            }  
        }  
        printf("%d %d\n", Min, Max);  
    }  
    return 0;  
}  

 

 
补充:软件开发 , C++ ,
CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,