这道题是刘汝佳的训练指南上的例题。
题目的意思是一根棍子上有好多蚂蚁,朝着不同的方向走,当两只蚂蚁撞到的时候就回头向着相反的方向走。要求输出在T时刻蚂蚁不同的位置,输出的时候按照输入的顺序。
在训练指南里面用到了运算符的重载,我也学到了运算符重载原来可以这样用。他先定义了一个ant型的结构体,记录输入的顺序,位置,方向。然后重载“<”运算符,对位置进行排序。这样就可以将ant型的数据传参数给sort函数。
还是不习惯用C语言里面的scanf函数,所以只有在输入比较多的地方用了scanf,其他的还是用cin。
#include<cstdio>
#include<iostream>
#include<algorithm>
using namespace std;
const int maxn=10000+5;
typedef struct ant{
int ord;
int p;
int d;
bool operator < (const ant & a) const{
return p<a.p;
}
};
ant befor[maxn],after[maxn];
int order[maxn];
char dir[][10]={"L","Turning","R"};
int main(){
int N;
scanf("%d",&N);
for(int kase=1;kase<=N;++kase){
int L,T,n;
scanf("%d %d %d",&L,&T,&n);
int i;
for(i=0;i<n;++i)
{
int p,d;
char c;
scanf("%d %c",&p,&c);
d=(c=='L'?(-1):1);
befor[i]=(ant){i,p,d};
after[i]=(ant){0,p+T*d,d};
}
sort(befor,befor+n);
for(i=0;i<n;++i)
{
order[befor[i].ord]=i;
}
sort(after,after+n);
cout<<"Case #"<<kase<<':'<<endl;
for(i=0;i<n;++i)
{
int a=order[i];
if(after[a].p<0||after[a].p>L){cout<<"Fell off"<<endl;continue;}
cout<<after[a].p<<' ';
if((a>0&&after[a].p==after[a-1].p)||(a<n-1&&after[a].p==after[a+1].p))
{
cout<<"Turning"<<endl;
}
else cout<<dir[after[a].d+1]<<endl;
}
cout<<endl;
}
return 0;
}