[POJ] [1852] Ants

Problem Description

Loading...

Problem Analysis

An IQ problem

n ants crawl at 1 cm per second on a pole of length L cm. When an ant reaches an endpoint of the pole, it falls off. Because the pole is too thin, when two ants meet, they cannot pass each other; they can only turn around and crawl back in opposite directions. For each ant, we know its distance xi from the left end of the pole, but we do not know its current orientation. Please calculate the shortest and longest time required for all ants to fall off the pole.

Typing it out from the book seems completely pointless… -.-

Anyway, it’s just counting, so let’s treat it as a break.

As the first somewhat formal problem in Programming Contest Challenge

When I first started thinking about it, I was stunned by the difficulty of this book -_-

Lamenting my lack of IQ

Then there’s this

image.png

The key is to realize that each ant’s movement can be understood as moving independently.

So when finding the shortest time, we only need to find

the ant farthest from the left or right endpoint (closest to the middle, facing the nearer edge)

(As expected, how much water a barrel can hold depends on the shortest plank, right?)

When finding the longest time, we only need to find

the ant farthest from the left or right endpoint (closest to an endpoint, facing the farther edge)

So the code is easy to write.

cpp
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
#include<cstdio>
#include<algorithm>
using namespace std;
int a[1000200];
int main() {
	int T,L,n,Tmin,Tmax;
	scanf("%d",&T);
	while(T--) {
		scanf("%d %d",&L,&n);
		for(int i=0; i<n; i++)
			scanf("%d",&a[i]);
		Tmin=Tmax=0;
		for(int i=0; i<n; i++)
			Tmin=max(Tmin,min(a[i],L-a[i]));
		for(int i=0; i<n; i++)
			Tmax=max(Tmax,max(a[i],L-a[i]));
		printf("%d %d\n",Tmin,Tmax);
	}
	return 0;
}

As expected, it really tests your IQ…

Recalling it again… I find I’m still a bit muddled…

-.-

Used a C++ coding approach

So I guess I got a first taste of it~

Problem link: 【POJ】[1852]Ants

​

Loading...