UVa 10881 Piotr's Ants 蚂蚁
2015-06-26 17:37
387 查看
题意:一根长度为L的木棍上有n只蚂蚁,每只蚂蚁要么向左爬要么向右爬。速度为1/s。两蚂蚁相撞时会同时掉头且掉头时间忽略不计。给出蚂蚁的初始位置和方向。求T时间后每只蚂蚁的位置和方向。
很有意思的题。这道题分析的重点在于如何处理相撞蚂蚁之后的变化。假设我们把每只蚂蚁编号1 ~ n。从效果上看来,两只蚂蚁相撞后,可以看做是并没有相撞而是对穿而过,然后两只蚂蚁互换了他们的编号。这样来看,我们只需要计算最终所有蚂蚁都在哪些位置,然后根据初始时每只蚂蚁的相对位置映射到最终状态的编号上。即可求出每只蚂蚁最终的位置和方向。而计算的时候由于按照刚才分析的等价效果,不需要考虑碰撞,所以按初始方向直接计算最终位置即可。
很有意思的题。这道题分析的重点在于如何处理相撞蚂蚁之后的变化。假设我们把每只蚂蚁编号1 ~ n。从效果上看来,两只蚂蚁相撞后,可以看做是并没有相撞而是对穿而过,然后两只蚂蚁互换了他们的编号。这样来看,我们只需要计算最终所有蚂蚁都在哪些位置,然后根据初始时每只蚂蚁的相对位置映射到最终状态的编号上。即可求出每只蚂蚁最终的位置和方向。而计算的时候由于按照刚才分析的等价效果,不需要考虑碰撞,所以按初始方向直接计算最终位置即可。
#include <iostream> #include <cstdio> #include <cmath> #include <cstring> #include <string> #include <algorithm> #include <stack> #include <queue> #include <vector> #include <map> #include <set> using namespace std; struct Ant { int id; int pos; char direction; bool turning; }; const int MAX = 10005; int L, T, n; Ant ant[MAX]; bool cmp_id(Ant x, Ant y) { return x.id < y.id; } bool cmp_pos(Ant x, Ant y) { return x.pos < y.pos; } void input() { scanf("%d%d%d", &L, &T, &n); char x; for(int i = 0; i < n; i++) { scanf("%d%c%c", &ant[i].pos, &x, &ant[i].direction); //这里x并没有用,只是为了处理输入 ant[i].id = i; ant[i].turning = false; } } void solve() { Ant finish[MAX]; //最终蚂蚁的所有状态 for(int i = 0; i < n; i++) { if(ant[i].direction == 'L') finish[i].pos = ant[i].pos - T; else finish[i].pos = ant[i].pos + T; finish[i].direction = ant[i].direction; } sort(finish, finish + n, cmp_pos); //将所有蚂蚁的最终状态按位置排序 sort(ant, ant + n, cmp_pos); //按蚂蚁相对位置排序,以便修改最终状态 for(int i = 0; i < n; i++) { ant[i].pos = finish[i].pos; //修改每个蚂蚁最终的位置 ant[i].direction = finish[i].direction; //修改每个蚂蚁最终方向 if(i > 0 && finish[i].pos == finish[i - 1].pos) ant[i - 1].turning = ant[i].turning = true; //位置相同的蚂蚁正在碰撞 } sort(ant, ant + n, cmp_id); //修改完后再按蚂蚁序号排序便于输出 for(int i = 0; i < n; i++) { if(ant[i].pos < 0 || ant[i].pos > L) //掉下木棍 printf("Fell off\n"); else { printf("%d ", ant[i].pos); if(ant[i].turning) printf("Turning\n"); else printf("%c\n", ant[i].direction); } } printf("\n"); } int main() { int T; scanf("%d", &T); for(int t = 1; t <= T; t++) { input(); printf("Case #%d:\n", t); solve(); } return 0; }
相关文章推荐
- Ubuntu 14.10 下进程实时IO监控iotop命令详解
- 【译】VisionMobile:2015 IOT大趋势(六)未来在此,开发者拥抱IoT
- 如何通过物联网获利
- HDU_4609_3-idiots
- Uva10881 - Piotr's Ants(蚂蚁)
- 【译】VisionMobile:2015 IOT大趋势(五)每人都是开发者
- 【译】VisionMobile:2015 IOT大趋势(四)消费者胜过CIO
- 针对物联网中MQTT协议的学习(一)
- 最近对物联网文章读后感
- riot.js学习【九】路由
- riot.js学习【八】观察者
- riot.js学习【七】脚本创建标签
- 物联网简介
- riot.js学习【六】杂烩2
- 物联网论坛
- 物联网论坛
- 闲聊物联网
- riot.js学习【五】杂烩1
- riot.js学习【四】表达式+Boolean属性
- riot.js学习【三】事件