题意:
一根长Lcm的木棍,n个蚂蚁在上面爬,1cm/s,给出它们的行走方向,蚂蚁相撞掉头继续走,问T秒后,各蚂蚁的状态。
思路:
蚂蚁一开始从左到右的顺序,与T秒后停止时的顺序存在映射关系,以此思路解题。
代码:
#include <iostream>
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <algorithm>
using namespace std;
struct ant {
int num;
int pos;
int d;
}ants[10005],print[10005];
int cmp(ant x,ant y) {
if (x.pos < y.pos)
return 1;
return 0;
}
int order[10005];
int main(){
int Case=0;
scanf("%d",&Case);
int index = 1;
while (Case--) {
memset(ants,0,sizeof(ants));
memset(print,0,sizeof(print));
memset(order, 0, sizeof(order));
int l, t, n;
scanf("%d%d%d",&l,&t,&n);
int i;
char c;
for (i = 0; i < n; i++) {
scanf("%d", &ants[i].pos);
cin >> c;
print[i].d=ants[i].d = (c == 'L') ?-1:1;
ants[i].num = i;
print[i].pos = ants[i].pos + (t*print[i].d);
}
sort(ants,ants+n,cmp);
for (i = 0; i < n; i++)
order[ants[i].num] = i;
sort(print,print+n,cmp);
for (i = 0; i < n-1; i++) {
if (print[i].pos == print[i + 1].pos)
print[i].d = print[i + 1].d = 0;
}
printf("Case #%d:\n",index++);
for (i = 0; i < n; i++){
int cur = order[i];
if (print[cur].pos < 0 || print[cur].pos>l)
printf("Fell off\n");
else {
if (print[cur].d == -1)
printf("%d L\n",print[cur].pos);
else if (print[cur].d == 1)
printf("%d R\n",print[cur].pos);
else
printf("%d Turning\n", print[cur].pos);
}
}
printf("\n");
//if(Case) 加了这句会WA,Tt_T
//原题的描述是:Print an empty line after each test case.
}
return 0;
}