uva10881 Piotr's Ants

本文提供了一个解决UVA在线评测系统中编号为10881的“蚂蚁赛跑”问题的C++实现方案。该问题出自刘汝佳《算法竞赛入门经典训练指南》一书的第一章。代码详细展示了如何通过输入蚂蚁的位置和方向,并模拟它们在一段时间后的状态变化,最终输出每只蚂蚁的状态。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源:http://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=456&page=show_problem&problem=1822

刘汝佳《算法竞赛入门经典训练指南》1.1例5

///2014.4.13
///10881
///刘汝佳《算法竞赛入门经典训练指南》1.1例5

#include <iostream>
#include <cstdio>
#include <string>
#include <cmath>
#include <algorithm>
#include <climits>
using namespace std;

struct Ant{
    int loc; ///location of the ant
    int dir; ///direction , left:-1 , right:1
    int id;  ///the number of cin order
};
int L,T,n;
Ant ant[10100];
int loc[10100];
bool cmp(Ant a,Ant b){
    return a.loc<b.loc;
}
bool cmp2(Ant a,Ant b){
    return a.id<b.id;
}
int main()
{
    // freopen("in","r",stdin);
    // freopen("out","w",stdout);
    int t;
    cin>>t;
    int cas = 1;
    while( t-- ){
        cin>>L>>T>>n;
        for(int i=0 ; i<n ; i++){
            cin>>ant[i].loc;
            char temp;
            cin>>temp;
            switch( temp ){
                case 'L': ant[i].dir = -1; break;
                case 'R': ant[i].dir = 1; break;
            }
            ant[i].id = i;
        }
        sort(ant,ant+n,cmp);
        for(int i=0 ; i<n ; i++){
            loc[i] = ant[i].id;
        }
        for(int i=0 ; i<n ; i++){
            ant[i].loc += ant[i].dir * T;
        }
        sort(ant,ant+n,cmp);
        for(int i=0 ; i<n ; i++){
            if( (ant[i].loc==ant[i+1].loc) && i+1<n ){
                ant[i].dir=ant[i+1].dir=0;
                i++;
            }
        }
        for(int i=0 ; i<n ; i++){
            ant[i].id = loc[i];
        }
        sort(ant,ant+n,cmp2);
        cout<<"Case #"<<cas++<<':'<<endl;
        for(int i=0 ; i<n ; i++){
            if( ant[i].loc<0 || ant[i].loc>L )
                cout<<"Fell off"<<endl;
            else{
                cout<<ant[i].loc<<" ";
                switch( ant[i].dir ){
                    case 1: cout<<"R"<<endl; break;
                    case 0: cout<<"Turning"<<endl; break;
                    case -1: cout<<"L"<<endl;break;
                }
            }
        }
        cout<<endl;
    }
    return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值