http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=20&page=show_problem&problem=1822
题意:一根长为L的木棒上有n只蚂蚁左右移动,1秒1个单位长度,碰撞后反向移动,问T秒后蚂蚁的位置与方向。
思路:碰撞后反方向和直接穿过相对位置来说是一样的,他们在木棒上的相对顺序是不变的。
#include <iostream>
#include <algorithm>
using namespace std;
#define MAXN 10010
struct Ant
{
int inputID; //记录输入的顺序
int pos; //起始位置
int direction; //方向 左-1,转身0,右1
const bool operator < (const struct Ant &a) const
{
return pos < a.pos;
}
}start[MAXN], end[MAXN];
const char status[][10] = {"L", "Turning", "R"};
int order[MAXN];//输入第i只对应结果第order[i]只
int main()
{
int K, L, t, n;
cin>>K;
for (int cas = 1; cas <= K; cas++)
{
printf("Case #%d:\n", cas);
cin>>L>>t>>n;
for (int i = 0; i < n; i++)
{
int p, d;
char ch;
scanf("%d %c", &p, &ch);
d = (ch == 'L' ? -1 : 1);
start[i].inputID = i;
start[i].pos = p;
start[i].direction = d;
end[i].inputID = 0;//id未知
end[i].pos = p + t * d;
end[i].direction = d;
}
//order数组
sort(start, start + n);
for (i = 0; i < n; i++)
order[start[i].inputID] = i;
//结果
sort(end, end + n);
for (i = 0; i < n - 1; i++)
if (end[i].pos == end[i + 1].pos) end[i].direction = end[i + 1].direction = 0;//修改在转身的蚂蚁方向
for (i = 0; i < n ;i++)
{
int a = order[i];
if (end[a].pos < 0 || end[a].pos > L) printf("Fell off\n");
else printf("%d %s\n", end[a].pos, status[end[a].direction + 1]);
}
printf("\n");
}
return 0;
}