UVa 10881 蚂蚁

https://vjudge.net/problem/UVA-10881

题意:

一根长度为L厘米的木棍上有n只蚂蚁,每只蚂蚁要么朝左爬,要么朝右爬,速度为1厘米/秒。当两只蚂蚁相撞时,二者同时掉头。给出每只蚂蚁的初始位置和朝向,计算T秒之后每只蚂蚁的位置。

思路:

首先,如果不考虑掉头的话,蚂蚁相遇时就是对穿而过,如果考虑掉头,局势是不会发生改变的,就是蚂蚁的位置不同。

比如蚂蚁1(2,R),蚂蚁2(4,L),经过3秒后,如果不考虑掉头,那么蚂蚁1(5,R),蚂蚁2(1,L)。如果考虑掉头,则蚂蚁1(1 , L),蚂蚁2(5 , R)。也就是说不管怎样,总有蚂蚁会在(1,L),也总有蚂蚁会在(5,R),所以一开始我们可以不用考虑掉头来计算出所有蚂蚁最后的状态,我们需要确定的就是哪只蚂蚁处于这个状态。

接下来的一点很重要,因为蚂蚁相撞后会掉头,所以蚂蚁的相对顺序是不会变的,也就是说最左边的蚂蚁肯定一直在最左边,从左往右第1只 蚂蚁也肯定一直处于第1只...这个想一下就可以理解了。

既然这样,最后只需要按照坐标排序然后和蚂蚁匹配就可以了。

 #include<iostream>
#include<algorithm>
using namespace std; int l, t, n; const int maxn = + ; struct node
{
int id;
int p;
int d; //方向,-1表示往左,0表示碰撞,1表示往右
bool operator <(const node& rhs) const
{
return p < rhs.p;
}
}before[maxn],after[maxn]; int order[maxn]; char dir[][] = { "L", "Turning", "R" }; int main()
{
ios::sync_with_stdio(false);
//freopen("D:\\txt.txt", "r", stdin);
int T;
int p;
char c;
int kase = ;
cin >> T;
while (T--)
{
cin >> l >> t >> n;
for (int i=; i < n; i++)
{
cin >> p >> c;
int d = c == 'L' ? - : ;
before[i].id = i;
before[i].p = p;
before[i].d = d;
after[i].id = ;
after[i].p = t*d + p;
after[i].d = d;
}
sort(before, before + n);
for (int i = ; i < n; i++)
{
order[before[i].id] = i;
} sort(after, after + n);
for (int i = ; i < n;i++)
if (after[i].p == after[i + ].p)
after[i].d = after[i + ].d = ; cout << "Case #" << ++kase << ":" << endl;
for (int i = ; i < n; i++)
{
int num = order[i];
if (after[num].p< || after[num].p>l) cout << "Fell off" << endl;
else cout << after[num].p << " " << dir[after[num].d + ] << endl;
}
cout << endl;
}
}
上一篇:PHP引用文件


下一篇:低版本系统兼容的ActionBar(四)添加Tab+添加自定义的Tab视图+Fragment