CCF-201803-2 碰撞的小球

时间:2024-01-17 11:56:26
问题描述
  数轴上有一条长度为L(L为偶数)的线段,左端点在原点,右端点在坐标L处。有n个不计体积的小球在线段上,开始时所有的小球都处在偶数坐标上,速度方向向右,速度大小为1单位长度每秒。
当小球到达线段的端点(左端点或右端点)的时候,会立即向相反的方向移动,速度大小仍然为原来大小。
当两个小球撞到一起的时候,两个小球会分别向与自己原来移动的方向相反的方向,以原来的速度大小继续移动。
现在,告诉你线段的长度L,小球数量n,以及n个小球的初始位置,请你计算t秒之后,各个小球的位置。
提示
  因为所有小球的初始位置都为偶数,而且线段的长度为偶数,可以证明,不会有三个小球同时相撞,小球到达线段端点以及小球之间的碰撞时刻均为整数。
同时也可以证明两个小球发生碰撞的位置一定是整数(但不一定是偶数)。
输入格式
  输入的第一行包含三个整数n, L, t,用空格分隔,分别表示小球的个数、线段长度和你需要计算t秒之后小球的位置。
第二行包含n个整数a1, a2, …, an,用空格分隔,表示初始时刻n个小球的位置。
输出格式
  输出一行包含n个整数,用空格分隔,第i个整数代表初始时刻位于ai的小球,在t秒之后的位置。
样例输入
3 10 5
4 6 8
样例输出
7 9 9
样例说明
  CCF-201803-2 碰撞的小球
样例输入
10 22 30
14 12 16 6 10 2 8 20 18 4
样例输出
6 6 8 2 4 0 4 12 10 2
数据规模和约定
  对于所有评测用例,1 ≤ n ≤ 100,1 ≤ t ≤ 100,2 ≤ L ≤ 1000,0 < ai < L。L为偶数。
保证所有小球的初始位置互不相同且均为偶数。
java 代码:
 import java.util.Collections;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Scanner; public class Main { public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
String line = sc.nextLine();
String[] split = line.split(" ");
int n = Integer.valueOf(split[0]);
int l = Integer.valueOf(split[1]);
int t = Integer.valueOf(split[2]); List<Ball> balls = new LinkedList<>(); String ballInfo = sc.nextLine();
String[] ballLocation = ballInfo.split(" ");
for (int i = 0; i < ballLocation.length; i++) {
balls.add(new Ball(true, Integer.valueOf(ballLocation[i])));
}
sc.close(); for (int i = 0; i < t; i++) {
for (Ball ball : balls) {
if (ball.direction) {
ball.position++;
} else {
ball.position--;
}
if (ball.position == 0 || ball.position == l) {
ball.direction = (!ball.direction);
}
}
List<Ball> tempBalls = new LinkedList<>();
Iterator<Ball> iterator = balls.iterator();
while (iterator.hasNext()) {
Ball ball = iterator.next();
iterator.remove();
if (balls.contains(ball)) {
balls.get(balls.indexOf(ball)).direction = !balls.get(balls.indexOf(ball)).direction;
ball.direction = !ball.direction;
}
tempBalls.add(ball);
}
balls=tempBalls; }
Collections.sort(balls, (Ball x, Ball y) -> {
return x.position - y.position;
});
String s = "";
for (Ball ball : balls) {
s += ball.position + " ";
}
System.out.print(s.substring(0, s.length() - 1)); } static class Ball {
// 小球运动方向 true 为向右
boolean direction;
// 小球位置
int position; public Ball(boolean fangxiang, int weizhi) {
super();
this.direction = fangxiang;
this.position = weizhi;
} @Override
public boolean equals(Object obj) {
Ball o = null;
if (obj instanceof Ball) {
o = (Ball) obj;
} else {
return false;
}
return o.position == this.position;
} } }