UVA-10881 Piotr's Ants (想法题)

题目大意:
一根长L厘米的木棍上有n只蚂蚁,每只蚂蚁有个开始的位置和爬行方向,速度为1.当两只蚂蚁相撞后,两者同时掉头继续爬行,求按输入顺序给出每只蚂蚁T秒后的位置后朝向。

思路:
1.每只蚂蚁相撞后同时掉头可以看做对穿而过,关键的问题就在于求位置的变化。

2.因为当两只蚂蚁相撞后,两者同时掉头继续爬行,所以最终所有的蚂蚁相对位置并没有变化,改变的只是朝向。

#include <cstdio>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10005;
int l,t,n;
struct Ant {
	int id;
	int dist;
	int pos;
}ant[N],finAnt[N];
char cmd[5];
bool cmpPos(Ant a,Ant b) {
	return a.pos < b.pos;
}
bool cmpId(Ant a,Ant b) {
	return a.id < b.id;
}
int main() {
	int T, star, cas = 1;
	scanf("%d",&T);
	while(T--) {
		scanf("%d%d%d",&l,&t,&n);
		for(int i = 0; i < n; i++) {
			scanf("%d%s",&star,cmd);
			ant[i].id = finAnt[i].id = i; //id
			
			if(cmd[0] == 'L') { //dist
				ant[i].dist = -1;
			}else {
				ant[i].dist = 1;
			}
			finAnt[i].dist = ant[i].dist;

			ant[i].pos = star; //pos
			finAnt[i].pos = star + ant[i].dist * t;
		}
		sort(ant,ant + n,cmpPos);
		sort(finAnt,finAnt + n,cmpPos);
		for(int i = 0; i < n; i++) {
			ant[i].pos = finAnt[i].pos;
			ant[i].dist = finAnt[i].dist;
		}
		for(int i = 0; i < n-1; i++) {
			if(ant[i].pos == ant[i+1].pos) {
				ant[i].dist = ant[i+1].dist = 0;
			}
		}
		sort(ant,ant + n,cmpId);
		printf("Case #%d:\n",cas++);
		for(int i = 0; i < n; i++) {
			if(ant[i].pos < 0 || ant[i].pos > l) {
				printf("Fell off\n");
			}else if(ant[i].dist == -1) {
				printf("%d ",ant[i].pos);
				printf("L\n");
			}else if(ant[i].dist == 1) {
				printf("%d ",ant[i].pos);
				printf("R\n");
			}else if(ant[i].dist == 0) {
				printf("%d ",ant[i].pos);
				printf("Turning\n");
			}
		}
		printf("\n");
	}
	return 0;
}

你可能感兴趣的:(uva,10881)