UVa 10881 Piotr's Ants 蚂蚁

本文介绍了一道有趣的编程题目——模拟木棍上蚂蚁的碰撞行为。通过分析蚂蚁碰撞后的等效行为,得出无需实际处理碰撞,只需根据初始方向计算最终位置。文章提供了一段完整的C++代码实现。

题意:一根长度为L的木棍上有n只蚂蚁,每只蚂蚁要么向左爬要么向右爬。速度为1/s。两蚂蚁相撞时会同时掉头且掉头时间忽略不计。给出蚂蚁的初始位置和方向。求T时间后每只蚂蚁的位置和方向。





很有意思的题。这道题分析的重点在于如何处理相撞蚂蚁之后的变化。假设我们把每只蚂蚁编号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;
}

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值