This question has two important attributes:
1: Take two ants for analysis. If they encounter this problem, they will turn around. In this case, we can see that their relative sequence remains unchanged; if they do not collide, the relative sequence remains unchanged;
In combination, the relative sequence of all ants will not change, that is, if A is on the left of B, then a is on the left of B.
2: If we only want to find the next n positions of the next n ants, then the two ants can continue when they are penetrating each other, because they do replace each other.
Based on these two steps, you can easily find the question.
This question is made by Liu lujia's book. Liu lujia's analysis is really amazing. It divides a question into two independent parts, which is very enlightening;
#include<stdio.h>#include<algorithm>using namespace std;const int maxn = 10000+100;struct Ant{ int pos; int dir;//-1,0,1 int ord;//µÚ¼¸Ö» bool operator<(const struct Ant &ans) const { return pos < ans.pos; }}before[maxn], after[maxn];int order[maxn];int tcase, L, T, N;char dirName[][10] = {"L", "Turning", "R"};void Init(){ char tmp[2]; for(int i = 0; i < N; i++) { scanf("%d%s", &before[i].pos, tmp); before[i].ord = i; if(tmp[0] == 'L') before[i].dir = -1; else before[i].dir = 1; after[i].pos = before[i].pos + T * before[i].dir; after[i].dir = before[i].dir; after[i].ord = before[i].ord; } sort(before, before + N); sort(after, after + N);}void Solve(){ for(int i = 0; i < N; i++) { order[before[i].ord] = i; } for(int i = 0; i < N - 1; i++) { if(after[i].pos == after[i+1].pos) { after[i].dir = 0; after[i+1].dir = 0; } } for(int i = 0; i < N; i++) { int ans = order[i]; if(after[ans].pos < 0 || after[ans].pos > L) printf("Fell off\n"); else printf("%d %s\n", after[ans].pos, dirName[after[ans].dir + 1]); }}int main(){ scanf("%d", &tcase); for(int i = 1; i <= tcase; i++) { scanf("%d%d%d", &L, &T, &N); Init(); printf("Case #%d:\n", i); Solve(); putchar('\n'); } return 0;}