問題描述:
在L cm長的杆子上有n只螞蟻,螞蟻的移動速度爲1 cm/s,題目並告知這些螞蟻的初始位置pos及將要移動的方向L or R。如果兩隻螞蟻相遇則各自方向倒置,即往原移動方向相反的方向移動。求最終各個螞蟻的位置及最終方向。
解題方法:
根據題目意思,終止時刻每隻螞蟻相對其他螞蟻的位置是穩定的,即一隻螞蟻不會穿過另一隻螞蟻。我們可以假設把每隻螞蟻看作一樣的,因爲其最終時刻的位置相對假設之前是一樣的,只是螞蟻不一樣而已,再把位置序列排序,依次對應具體的螞蟻即可。
#include <iostream>
#include <algorithm>
#include <string>
#include <vector>
#include <map>
#define MAX(a,b) (a)>(b)?(a):(b)
using namespace std;
const int MAXSIZE = 10010;
int index[MAXSIZE];
struct ANT{ // save the position and its direction
int id;
int pos;
char dir;
};
vector<ANT> origin, finish;
bool cmp(const ANT &p1,const ANT &p2){
return p1.pos < p2.pos;
}
int main()
{
int N,Case=0; // N test cases
int L, T, n; // L cm, T s, n ants
int i,j;
scanf("%d", &N);
while (N--){
i = 0;
origin.clear();
finish.clear();
scanf("%d %d %d", &L, &T, &n);
while (n--){ //n ants
ANT ant;
scanf("%d %c", &ant.pos, &ant.dir);
ant.id = i++;
origin.push_back(ant);
}
for (j = 0; j < i; j++){
ANT ant;
ant.pos = (origin[j].dir == 'L') ? origin[j].pos - T : origin[j].pos + T;
ant.dir = origin[j].dir;
finish.push_back(ant);
}
sort(finish.begin(), finish.end(), cmp);
sort(origin.begin(), origin.end(), cmp);
for (j = 0; j < i; j++){
index[origin[j].id] = j;
}
cout << "Case #" << ++Case << ":" << endl;
for (j = 0; j < i; j++){
int tmpIndex = index[j];
if (finish[tmpIndex].pos<0 || finish[tmpIndex].pos>L){
cout << "Fell off" << endl;
continue;
}
cout << finish[tmpIndex].pos << " ";
if ((tmpIndex - 1 >= 0 && finish[tmpIndex - 1].pos == finish[tmpIndex].pos) || (tmpIndex + 1<i&&finish[tmpIndex + 1].pos == finish[tmpIndex].pos)){
cout << "Turning" << endl;
}
else {
cout << finish[tmpIndex].dir << endl;
}
}
cout << endl;
}
return 0;
}