poj1852 Ants ——想法题、水题
October 21, 2013
水题
求最短时间和最长时间。
当两个蚂蚁相遇的时候,可以看做两个蚂蚁穿过,对结果没有影响。O(N)的复杂度
c++版:
#include <cstdio>
#define min(a, b) (a) < (b) ? (a) : (b)
#define max(a, b) (a) > (b) ? (a) : (b)
int main(void)
{
#ifndef ONLINE_JUDGE
freopen("in.txt", "r", stdin);
#endif // ONLINE_JUDGE
int Case;
scanf("%d", &Case);
int n, L, Min, Max;
while (Case--) {
Min = -1; Max = -1;
scanf("%d%d", &L, &n);
int tmp;
while (n--) {
scanf("%d", &tmp);
int t1 = min(tmp, L - tmp);
int t2 = max(tmp, L - tmp);
if (Min < t1)
Min = t1;
if (Max < t2)
Max = t2;
}
printf("%d %d\n", Min, Max);
}
return 0;
}
Java版:
import java.util.*;
public class ants {
public static void main(String[] args) {
// TODO Auto-generated method stub
Scanner input = new Scanner(System.in);
int Case;
Case = input.nextInt();
while (Case-- != 0) {
int L;
int n;
L = input.nextInt();
n = input.nextInt();
int Max, Min;
Max = Min = 0;
while (n-- != 0) {
int tmp;
tmp = input.nextInt();
int Left = tmp, Right = L - tmp;
if (Left < Right) {
Min = (Min < Left ? Left : Min);
Max = (Max < Right ? Right : Max);
}
else {
Min = (Min < Right ? Right : Min);
Max = (Max < Left ? Left : Max);
}
}
System.out.println(Min + " " + Max);
}
}
}
其实Java写起来也不错的。