Uva 10881 Piotr's Ants (模拟+思维)

本文讨论了蚂蚁在木棒上移动碰撞后位置与方向的问题,通过两种思考方式解决,包括碰撞后蚂蚁互穿得出的位置和最终状态不变。详细介绍了算法实现,包括输入参数解析、状态转换和输出结果的生成。

题意:一根长为L的木棒上有n只蚂蚁左右移动,1秒1个单位长度,碰撞后反向移动,问T秒后蚂蚁的位置与方向。

题目链接:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&page=show_problem&category=20&problem=1822

解题两个思想:

1、两只蚂蚁相撞后假设互穿而过得最终各蚂蚁位置;

2、终态各蚂蚁的相对位置不变,与始态相同。


#include<cstdio>
#include<iostream>
#include<cstring>
#include<algorithm>
using namespace std;

char edst[][10]={"Turning","L","R"};
int temp[10010];     //第i只蚂蚁的最终状态在temp[i]中

struct ant
{
    int pos,id;
    int state;  //0=碰撞,1=向左,2=向右
}s[10010],e[10010];

bool cmp(ant x,ant y)
{
    return x.pos<y.pos;
}

int main()
{
    int T,L,t,n;
    char dir;
    scanf("%d",&T);
    for(int ca=1;ca<=T;ca++)
    {
        scanf("%d%d%d",&L,&t,&n);
        for(int i=0;i<n;i++)
        {
            scanf("%d %c",&s[i].pos,&dir);
            if(dir=='L')
            {
                s[i].state=e[i].state=1;
                e[i].pos=s[i].pos-t;
            }
            else
            {
                e[i].pos=s[i].pos+t;
                s[i].state=e[i].state=2;
            }
            s[i].id=i;
        }
        sort(s,s+n,cmp);
        for(int i=0;i<n;i++)  //记录输入的顺序
            temp[s[i].id]=i;
        sort(e,e+n,cmp);
        for(int i=0;i<n-1;i++)   //终态是否正在碰撞
        {
            if(e[i].pos==e[i+1].pos)
            {
               e[i].state=0;
               e[i+1].state=0;
            }
        }
        printf("Case #%d:\n",ca);
        for(int i=0;i<n;i++)
        {
            if(e[temp[i]].pos>L||e[temp[i]].pos<0)
                printf("Fell off\n");
            else
                printf("%d %s\n",e[temp[i]].pos,edst[e[temp[i]].state]);  //还原顺序再输出
        }
        printf("\n");
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值