(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;
}