“One thing is for certain: there is no stopping them;
the ants will soon be here. And I, for one, welcome our
new insect overlords.”
Kent Brockman
Piotr likes playing with ants. He has n of them on a horizontal pole L cm long. Each ant is facingeither left or right and walks at a constant speed of 1 cm/s. When two ants bump into each other, theyboth turn around (instantaneously) and start walking in opposite directions. Piotr knows where eachof the ants starts and which direction it is facing and wants to calculate where the ants will end up Tseconds from now.
Input
The first line of input gives the number of cases, N. N test cases follow. Each one starts with a linecontaining 3 integers: L , T and n (0 ≤ n ≤ 10000). The next n lines give the locations of the n ants(measured in cm from the left end of the pole) and the direction they are facing (L or R).
Output
For each test case, output one line containing ‘Case #x:’ followed by n lines describing the locationsand directions of the n ants in the same format and order as in the input. If two or more ants are atthe same location, print ‘Turning’ instead of ‘L’ or ‘R’ for their direction. If an ant falls off the polebefore T seconds, print ‘Fell off’ for that ant. Print an empty line after each test case.
Sample Input
2
10 1 4
1 R
5 R
3 L
10 R
10 2 3
4 R
5 L
8 R
Sample Output
Case #1:
2 Turning
6 R
2 Turning
Fell off
Case #2:
3 L
6 R
10 R
问题链接:UVa10881 Piotr's Ants。
问题简述:
一根长L厘米的木棍上有n只蚂蚁,已知每只蚂蚁有个开始的位置和爬行方向,速度为1。当两只蚂蚁相撞后,两者同时掉头继续爬行,求按输入顺序输出每只蚂蚁T秒后的位置和朝向。
问题分析:
蚂蚁碰头后,仍然是一只往左另一只往右,所以可以看作是各自继续行走。
T秒后位置,有可能变为负或大于木棍的长度,那就是掉落了。
不按照位置进行排序,就无法知道T秒后哪些蚂蚁调头。
过T秒后,蚂蚁的相对位置是不变的,所以按照之前的顺序进行输出即可。
程序说明:(略)
参考链接:(略)
题记:(略)
AC的C++程序如下:
/* UVa10881 Piotr's Ants */
#include <iostream>
#include <cstdio>
#include <algorithm>
using namespace std;
const char *dirname[] = {"L", "Turning", "R"};
const int N = 10000;
struct _ant {
int no; // 序号
int pos; // 位置
int direction; // 方向:0-2(dirname)
bool operator < (const _ant& a) const {
return pos<a.pos;
}
} before[N], after[N];
int order[N];
int main()
{
int allcase, l, t, n, pos;
char direction;
scanf("%d", &allcase);
for(int k=1; k<=allcase; k++) {
printf("Case #%d:\n", k);
scanf("%d%d%d", &l, &t, &n);
for(int i=0; i<n; i++) {
scanf("%d %c", &pos, &direction);
before[i] = _ant{i, pos, (direction == 'L' ? 0 : 2)};
after[i] = _ant{0, pos + (direction == 'L' ? -t : t), (direction == 'L' ? 0 : 2)};
}
// 按蚂蚁位置排序
sort(before, before + n);
for(int i=0; i<n; i++)
order[before[i].no] = i;
// 计算终止状态:按蚂蚁位置排序,如果相邻位置相同则置为掉头状态
sort(after, after + n);
for(int i=0; i<n-1; i++)
if(after[i].pos == after[i + 1].pos)
after[i].direction = after[i + 1].direction = 1;
// 输出结果
for(int i=0; i<n; i++) {
int j = order[i];
if(after[j].pos < 0 || after[j].pos > l)
printf("Fell off\n");
else
printf("%d %s\n", after[j].pos, dirname[after[j].direction]);
}
printf("\n");
}
return 0;
}