您的位置:首页 > 大数据 > 物联网

UVA 10881_Piotr's Ant

2016-01-20 16:22 204 查看
问题描述:

在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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++ 算法 uva