CCF 201803-2碰撞的小球 (100分)

(1)题目描述

在这里插入图片描述

(2)算法思想

首先确定一个前提:小球由于会产生碰撞,其相对位置不变,即左右关系不变。
得到了这一个前提在模拟小球之间的碰撞时只需与其前一位置的小球进行位置判断即可,避免了双重循环的O(n^2)复杂度(经测试双重循环也并不会超时)。
然后再模拟一下碰壁情况即可。

(3)代码实现

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

struct ball {
	int pos;
	int speed;
	int index;
};

bool cmp_pos(ball b1, ball b2) {
	return b1.pos<b2.pos;
}

bool cmp_index(ball b1, ball b2) {
	return b1.index<b2.index;
}

int main() {
	int N,L,T;
	cin>>N>>L>>T;
	ball B[N];
	for(int i=0; i<N; i++) {
		B[i].speed=1;
		B[i].index=i;
		cin>>B[i].pos;
	}
	sort(B,B+N,cmp_pos);
	for(int t=0; t<T; t++) {
		for(int i=0; i<N; i++) {
			B[i].pos+=B[i].speed;
			if(B[i].pos==0 || B[i].pos==L)
				B[i].speed*=(-1);
		}
		for(int i=0; i<N-1; i++) {
			if(B[i].pos==B[i+1].pos) {
				B[i].speed*=(-1);
				B[i+1].speed*=(-1);
			}
		}
	}
	sort(B,B+N,cmp_index);
	for(int i=0; i<N; i++)
		cout<<B[i].pos<<" ";
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值