Piotr's Ants
Time Limit: 2 seconds
Piotr likes playing with ants. He has n of them on a horizontal pole L cm long. Each ant is facing either left or right and walks at a constant speed of 1 cm/s. When two ants bump into each other, they both turn around (instantaneously) and start walking in opposite directions. Piotr knows where each of the ants starts and which direction it is facing and wants to calculate where the ants will end up T seconds from now.Kent Brockman
Input
The first line of input gives the number of cases, N. N test cases follow. Each one starts with a line containing 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 locations and directions of the n ants in the same format and order as in the input. If two or more ants are at the same location, print "Turning" instead of "L" or "R" for their direction. If an ant falls off the pole before Tseconds, 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 题目大意:一根长度为L厘米的木棍上有n只蚂蚁,每只蚂蚁要么朝左爬要么朝右爬,速度为1厘米/秒。当两只蚂蚁相撞时,二者同时掉头(掉头时间忽略不计)。给出每只蚂蚁初始位置和朝向,计算T秒之后每只蚂蚁的位置。 分析:在远处观察蚂蚁运动,由于黑点太小,所以当蚂蚁碰撞掉头时,看上去和两个点“对穿而过”没有任何区别。换句话说,如果把蚂蚁看成没有区别的小点,那么只需独立计算出每只蚂蚁在T时刻的位置即可。比如,3只蚂蚁,蚂蚁1=(3,R),蚂蚁2=(3,L),蚂蚁3=(4,L),则两秒钟之后,3只蚂蚁分别为(3,R),(1,L)和(2,L)。
而且所有蚂蚁的相对顺序保持不变,因此把所有目标位置从小到大排序,则从左到右的每个位置对应于初始状态下从左到右的每只蚂蚁。由于原题中的蚂蚁不一定按照从左到右的顺序输入,还需要预处理计算出输入中的第i只蚂蚁的序号order[i]。 代码如下:
#include<cstdio>
#include<algorithm>
using namespace std; const int maxn = + ; struct Ant {
int id; // 输入顺序
int p; // 位置
int d; // 朝向。 -1: 左; 0:转身中; 1:右
bool operator < (const Ant& a) const {
return p < a.p;
}
} before[maxn], after[maxn]; const char dirName[][] = {"L", "Turning", "R"}; int order[maxn]; // 输入的第i只蚂蚁是终态中的左数第order[i]只蚂蚁 int main() {
int K;
scanf("%d", &K);
for(int kase = ; kase <= K; kase++) {
int L, T, n;
printf("Case #%d:\n", kase);
scanf("%d%d%d", &L, &T, &n);
for(int i = ; i < n; i++) {
int p, d;
char c;
scanf("%d %c", &p, &c);
d = (c == 'L' ? - : );
before[i] = (Ant){i, p, d};
after[i] = (Ant){, p+T*d, d}; // 这里的id是未知的
} // 计算order数组
sort(before, before+n);
for(int i = ; i < n; i++)
order[before[i].id] = i; // 计算终态
sort(after, after+n);
for(int i = ; i < n-; i++) // 修改碰撞中的蚂蚁的方向
if(after[i].p == after[i+].p) after[i].d = after[i+].d = ; // 输出结果
for(int i = ; i < n; i++) {
int a = order[i];
if(after[a].p < || after[a].p > L) printf("Fell off\n");
else printf("%d %s\n", after[a].p, dirName[after[a].d+]);
}
printf("\n");
}
return ;
}