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.
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.
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.
2 10 3 2 6 7 214 7 11 12 7 13 176 23 191
4 8 38 207
最短距离:每只蚂蚁都往离自己最近的边缘走,离边缘最远的蚂蚁到达边缘所需时间即为最短时间;
最长距离:每只蚂蚁往离自己最远的边缘走,离边缘最远的蚂蚁到达边缘所用时间即为最长时间;有人会说,碰面之后会改变前进方向,但这并不影响每只蚂蚁所走距离,碰面后改变方向可以理解为两只蚂蚁互换灵魂,继续向开始方向前进,只是利用不同的身体走完了一段路程;
有一点需要注意,输入用scanf,如果用cin会T;但是如果加上std::ios::sync_with_stdio(false);这句话用cin也能过;有兴趣了解scanf与cin的区别可以看看这位大佬的博客点击打开链接
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
int ant[1000005];
int main(){
int T;
cin >> T;
while(T--){
int length, num;
cin >> length >> num;
int minn=1000000, maxx=0;
int l=0, r=0;
for(int i=0; i<num; i++){
scanf("%d",&ant[i]);
minn=min(minn, ant[i]);
maxx=max(maxx, ant[i]);
if(ant[i]>=(length+1)/2) r=max(r, length-ant[i]);
else l=max(l, ant[i]);
}
int min_t=max(l, r);
int max_t=max(length-minn, maxx);
cout << min_t << ' ' << max_t << endl;
}
return 0;
}
改了之后cin也过了;
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include <iostream>
#include <algorithm>
using namespace std;
int ant[1000005];
int main(){
std::ios::sync_with_stdio(false);
int T;
cin >> T;
while(T--){
int length, num;
cin >> length >> num;
int minn=1000000, maxx=0;
int l=0, r=0;
for(int i=0; i<num; i++){
cin >> ant[i];
minn=min(minn, ant[i]);
maxx=max(maxx, ant[i]);
if(ant[i]>=(length+1)/2) r=max(r, length-ant[i]);
else l=max(l, ant[i]);
}
int min_t=max(l, r);
int max_t=max(length-minn, maxx);
cout << min_t << ' ' << max_t << endl;
}
return 0;
}