UVa 10881 蚂蚁(等效变换)

这篇博客讨论了UVa 10881编程题目,涉及蚂蚁在长木棒上移动的问题。当蚂蚁相撞后会反向移动,但它们在木棒上的相对位置保持不变。这是一个关于碰撞和相对顺序的数学问题。

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

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

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

思路:碰撞后反方向和直接穿过相对位置来说是一样的,他们在木棒上的相对顺序是不变的。

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

#define MAXN 10010
struct Ant
{
	int inputID;	//记录输入的顺序
	int pos;		//起始位置
	int direction;	//方向 左-1,转身0,右1
	const bool operator < (const struct Ant &a) const
	{
		return pos < a.pos;
	}
}start[MAXN], end[MAXN];

const char status[][10] = {"L", "Turning", "R"};

int order[MAXN];//输入第i只对应结果第order[i]只


int main()
{
	int K, L, t, n;
	cin>>K;
	for (int cas = 1; cas <= K; cas++)
	{
		printf("Case #%d:\n", cas);
		cin>>L>>t>>n;
		for (int i = 0; i < n; i++)
		{
			int p, d;
			char ch;
			scanf("%d %c", &p, &ch);
			d = (ch == 'L' ? -1 : 1);

			start[i].inputID = i;
			start[i].pos = p;
			start[i].direction = d;

			end[i].inputID = 0;//id未知
			end[i].pos = p + t * d;
			end[i].direction = d;
		}
		
		//order数组
		sort(start, start + n);
		for (i = 0; i < n; i++)
			order[start[i].inputID] = i;

		//结果
		sort(end, end + n);
		for (i = 0; i < n - 1; i++)
			if (end[i].pos == end[i + 1].pos) end[i].direction = end[i + 1].direction = 0;//修改在转身的蚂蚁方向
		
		for (i = 0; i < n ;i++)
		{
			int a = order[i];
			if (end[a].pos < 0 || end[a].pos > L) printf("Fell off\n");
			else printf("%d %s\n", end[a].pos, status[end[a].direction + 1]);
		}
		printf("\n");
	}
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值