Piotr's Ants(蚂蚁)

来源:互联网 发布:开淘宝店快递怎么弄 编辑:程序博客网 时间:2024/04/29 05:20

Piotr likes playing with ants. He has n of them on a horizontal poleL 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 upT seconds from now.

Input
The first line of input gives the number of cases, N. Ntest cases follow. Each one starts with a line containing 3 integers:L ,T andn(0 <= n <= 10000). The nextn lines give the locations of then 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 byn lines describing the locations and directions of then 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 polebeforeT 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 R2

Turning

Fell off

Case #2:

3 L

6 R

10 R

分析:

      大牛的想法就是cool,比我写的效率高多了。大牛思想:两只蚂蚁相撞,可以看作是“对穿而过”,只不过要分清楚谁是谁。那么怎么知道谁是谁呢?由于蚂蚁的相对顺序保持不变,所以把他们进行从小到大的排序,所以当相撞时,取对方蚂蚁的方向

代码如下:

#include <cstdio>#include <algorithm>using namespace std;struct Ant {int id;//表示输入顺序int pos;//蚂初始位置int dir;//-1:左;0:转身中;1:右bool operator< (const Ant & a) const{return pos < a.pos;}}before[10000],after[10000];const char dirName[][10] = {"L","Turning","R"};int order[10000];//输入的第i只蚂蚁是终状态中的左数第order[i]只蚂蚁,这是理解重点int main(){int x,count = 0;scanf("%d",&x);while (x--){int L,T,n;scanf("%d%d%d",&L,&T,&n);for (int i = 0; i < n; i++){int pos,dir;char c;scanf("%d %c",&pos,&c);dir = (c == 'L' ? -1 : 1);before[i].id = i;before[i].pos = pos;before[i].dir = dir;after[i].id = 0;//这里指id是未知的after[i].pos = pos + T * dir;//计算T秒之后的位置after[i].dir = dir;}//计算order数组sort(before,before + n);for (int j = 0; j < n; j++){order[before[j].id] = j;}//计算终态sort(after,after + n);for (int k = 0; k < n - 1; k++)//修改碰撞中的蚂蚁方向{if (after[k].pos == after[k + 1].pos){after[k].dir = after[k + 1].dir = 0;}}//输出结果printf("Case #%d:\n",++count);for (int l = 0; l < n; l++){int a = order[l];if (after[a].pos < 0 || after[a].pos > L){printf("Fell off\n");}else{printf("%d %s\n",after[a].pos,dirName[after[a].dir + 1]);}}}return 0;}


原创粉丝点击