2021-02-08

CCF-CSP\专题\题型A 简单模拟\201803-2 碰撞的小球

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

/* run this program using the console pauser or add your own getch, system("pause") or input loop */

int N,L,T;
// N个小球,区间右端点为L,模拟T秒。

struct Ball {
	int id;
	int dir; // 方向,0右,1左。 
	int pos; // 坐标轴的位置。
};

enum {
	DirR=0,
	DirL=1
};

#define MAXN 105

Ball bs[MAXN];
// 下一个状态。 
Ball next[MAXN];

bool cmpByPos(Ball& a, Ball& b) {
	return a.pos < b.pos;
}
bool cmpById(Ball& a, Ball& b) {
	return a.id < b.id;
}

void Print() {
	for (int i=0;i<N;++i) {
		printf("%d%s", bs[i].pos, i==N-1?"\n":" ");
	}
}

int main(int argc, char** argv) {
	scanf("%d%d%d",&N,&L,&T);
	for (int i=0;i<N;++i) {
		scanf("%d", &bs[i].pos);
		bs[i].id=i;
	}
	/*
	输入的小球的顺序,也是输出的顺序,但是不是进行模拟的初始顺序。
	先把小球按照位置从小到大排序,模拟后,再按照输入顺序排序,然后输出。
	*/
	sort(bs, bs+N, cmpByPos);
	
	// 进行T次模拟。
	while (T--) {
//		Print();
		
		for (int i=0;i<N;++i) {
			/*
			对于每个小球,根据当前状态计算下一个状态。
			*/
			Ball b=bs[i];
			// 注意复制id。 
			next[i].id=b.id;
			
			// 检查左墙。 
			// 注意,球的相对位置不变,即只有最左边的球才能撞左墙。 
			if (i == 0 && b.pos == 1 && b.dir == DirL) {
				next[i].pos=0;
				next[i].dir=DirR;
			} else if (i==N-1 && b.pos == L-1 && b.dir == DirR) {
				// 检查右墙。
				next[i].pos=L;
				next[i].dir=DirL; 
			} else if (i>0 && b.dir==DirL && bs[i-1].dir==DirR && b.pos-bs[i-1].pos==2) {
				// 和左边的球碰撞。
				next[i].pos=b.pos-1;
				next[i].dir=DirR;				 
			} else if (i<N-1 && b.dir==DirR && bs[i+1].dir==DirL && bs[i+1].pos-b.pos==2) {
				// 和右边的球碰撞。
				next[i].pos=b.pos+1;
				next[i].dir=DirL;
			} else {
				// 没有碰撞发生。
				next[i].dir=b.dir;
				if (b.dir == DirL) {
					next[i].pos=b.pos-1;
				} else {
					next[i].pos=b.pos+1;
				}
			}
		}
		memcpy(bs, next, sizeof(Ball)*N);
	}
	
	sort(bs, bs+N, cmpById);
	Print();
	
	return 0;
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值