UVA - 10881:Piotr's Ants

Piotr’s Ants

来源:UVA

标签:

参考资料:

相似题目:

题目

Piotr likes playing with ants. He has n of them on a horizontal pole L cm long. Each ant is facing either left or right and walks at a constant speed of 1 cm/s. When two ants bump into each other, they both turn around (instantaneously) and start walking in opposite directions. Piotr knows where each of the ants starts and which direction it is facing and wants to calculate where the ants will end up T seconds from now.

输入

The first line of input gives the number of cases, N. N test cases follow. Each one starts with a line containing 3 integers: L , T and n (0 ≤ n ≤ 10000). The next n lines give the locations of the n ants (measured in cm from the left end of the pole) and the direction they are facing (L or R).

输出

For each test case, output one line containing ‘Case #x:’ followed by n lines describing the locations and directions of the n ants in the same format and order as in the input. If two or more ants are at the same location, print ‘Turning’ instead of ‘L’ or ‘R’ for their direction. If an ant falls off the pole before T seconds, print ‘Fell off’ for that ant. Print an empty line after each test case.

输入样例

2
10 1 4
1 R
5 R
3 L
10 R
10 2 3
4 R
5 L
8 R

输出样例

Case #1:
2 Turning
6 R
2 Turning
Fell off


Case #2:
3 L
6 R
10 R

参考代码

#include
#include
#define MAXN 10005
using namespace std;
struct Ant{
	int index;
	int order;
	int pos;
	int dir;
}ant[MAXN];

bool cmp_order(Ant a, Ant b){
	return a.pos<b.pos;
}

bool cmp_index(Ant a, Ant b){
	return a.index<b.index;
}

int main(){
	int m;
	scanf("%d\n",&m);
	for(int i=1;i<=m;i++){
		int L,T,n;
		scanf("%d%d%d",&L,&T,&n);
		char str[5];
		for(int j=0;j<n;j++){
			scanf("%d%s",&ant[j].pos,str);
			ant[j].index=j;
			if(str[0]=='L') ant[j].dir=-1;
			else ant[j].dir=1;
		}
		sort(ant,ant+n,cmp_order);//对蚂蚁进行位置排序 
		for(int j=0;j<n;j++){//记录蚂蚁的位置序号 
			ant[j].order=j;
		}
		Ant now[MAXN];//T之后的蚂蚁 
		for(int j=0;j<n;j++){//计算蚂蚁的位置以及方向 
			now[j].pos=ant[j].pos+ant[j].dir*T;
			now[j].dir=ant[j].dir;
		}
		sort(now,now+n,cmp_order);//对蚂蚁进行位置排序 
		sort(ant,ant+n,cmp_index);//还原最初蚂蚁的位置 
		printf("Case #%d:\n",i);
		for(int j=0;j<n;j++){
			int at=ant[j].order;
			if(now[at].pos>=0 && now[at].pos<=L){
				printf("%d ",now[at].pos);
				if(at>=1 && now[at-1].pos==now[at].pos || at<n-1 && now[at+1].pos==now[at].pos){
					printf("Turning\n");
				}else{
					printf("%s\n",now[at].dir==-1?"L":"R");
				}
			}else{
				printf("Fell off\n");
			}
		}
		printf("\n");
	}
	return 0;
} 

你可能感兴趣的:(【记录】算法题解)