用了另一组克隆的结构数组保存上一秒的信息,这样不会有冲突
#include "iostream"
using namespace std;
int main() {
int n, L, t;
cin >> n >> L >> t;
struct str {
int x;//表示球的位置
int dir = 1;//1表示向右,-1表示向左,开始时均为1
} ball[1005];
str copy[1005];
for (int i = 0; i < n; i++) {
cin >> ball[i].x;
copy[i].x = ball[i].x;
}
int now = 0;
int bang = 0;
while ((now++) != t) {
for (int i = 0; i < n; i++) {
if (copy[i].dir == 1 && copy[i].x == L) {//在最右边且要向右
ball[i].dir = -1;//方向改变==
ball[i].x--;//向左一格
}
else if (copy[i].dir == -1 && copy[i].x == 0) {//在最左边且要向左
ball[i].dir = 1;//方向改变
ball[i].x++;//向右一格
}
else {
bang = 0;
for (int j = 0; j < n; j++) {
if (copy[i].x == copy[j].x && i != j) {
ball[i].dir = -copy[i].dir;
ball[j].dir = -copy[j].dir;
ball[i].x = copy[i].x - copy[i].dir;
ball[j].x = copy[j].x - copy[j].dir;
bang = 1;
break;
}
}
if (bang == 0) {//没有碰撞的
ball[i].x = copy[i].x + copy[i].dir;
}
}
}
for (int i = 0; i < n; i++) {
copy[i].dir = ball[i].dir;
copy[i].x = ball[i].x;
}
}
for (int i = 0; i < n; i++) {
cout << ball[i].x << " ";
}
return 0;
}