问题链接: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:
", 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
");
else
printf("%d %s
", after[j].pos, dirname[after[j].direction]);
}
printf("
");
}
return 0;
}