题目大意:
给出一根长为L的木棍,让蚂蚁在上面爬,给出蚂蚁的初始位置和走的方向,两只蚂蚁若相遇就往相反方向走,求T时间后蚂蚁的位置。
思路:
这题跟某一题也是蚂蚁的很相似,只是另外一题求的是最短时间最长时间之类的。蚂蚁相遇后反向其实等价于没有掉头,继续往前走,只是这时候不是同一只蚂蚁在走了而已,这一题蚂蚁的顺序是最开始从左到右的蚂蚁,到最后位置也是从左到右排序的。那么就可以利用这一特性做题目。
代码:
#include <iostream>
using namespace std;
#include <cstring>
#include <stdio.h>
#include <algorithm>
const int maxn = 10005;
struct ants {
int flag;
int id;
int pos;
}before[maxn],after[maxn];
int cmp(const void *a,const void *b) {
struct ants *c = (ants *)a;
struct ants *d = (ants *)b;
return c->pos - d-> pos;
}
int order[maxn];
const char situation[3][20] = {"L","Turning","R"};
int main() {
int N,K = 1,L,T,n;
scanf("%d",&N);
while(N--) {
scanf("%d%d%d",&L,&T,&n);
//scanf("%d",&T);
// scanf("%d",&n);
for(int i = 0 ; i < n;i++){
int p;
char c;
scanf("%d %c",&p,&c);
// printf("%c\n",c);
int d = (c == 'L'?-1:1);
before[i].flag = d;
before[i].pos = p;
before[i].id = i;
after[i].flag = d;
after[i].pos = p + d*T;
after[i].id = 0;
// before[i] = (ants){d,i,p};
// after[i] = (ants){d,0,p+d*T};
}
// printf("%d\n",before[1].pos);
printf("Case #%d:\n",K++);
qsort(before,n,sizeof(before[0]),cmp);
// printf("%d\n",before[0].pos);
for(int i = 0 ; i < n; i++){
order[before[i].id] = i;
}
qsort(after,n,sizeof(after[0]),cmp);
for(int i = 0; i < n - 1; i++)
if(after[i].pos == after[i + 1].pos) after[i].flag = after[i + 1].flag= 0;
for(int i = 0 ; i < n ; i++){
int a = order[i];
if(after[a].pos < 0 || after[a].pos > L) printf("Fell off\n");
else
printf("%d %s\n",after[a].pos,situation[after[a].flag+1]);
}
printf("\n");
}
return 0;
}