问题描述
数轴上有一条长度为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
样例说明
样例输入
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 代码:
1 import java.util.Collections; 2 import java.util.Iterator; 3 import java.util.LinkedList; 4 import java.util.List; 5 import java.util.Scanner; 6 7 public class Main { 8 9 public static void main(String[] args) {10 Scanner sc = new Scanner(System.in);11 String line = sc.nextLine();12 String[] split = line.split(" ");13 int n = Integer.valueOf(split[0]);14 int l = Integer.valueOf(split[1]);15 int t = Integer.valueOf(split[2]);16 17 Listballs = new LinkedList<>();18 19 String ballInfo = sc.nextLine();20 String[] ballLocation = ballInfo.split(" ");21 for (int i = 0; i < ballLocation.length; i++) {22 balls.add(new Ball(true, Integer.valueOf(ballLocation[i])));23 }24 sc.close();25 26 for (int i = 0; i < t; i++) {27 for (Ball ball : balls) {28 if (ball.direction) {29 ball.position++;30 } else {31 ball.position--;32 }33 if (ball.position == 0 || ball.position == l) {34 ball.direction = (!ball.direction);35 }36 }37 List tempBalls = new LinkedList<>();38 Iterator iterator = balls.iterator();39 while (iterator.hasNext()) {40 Ball ball = iterator.next();41 iterator.remove();42 if (balls.contains(ball)) {43 balls.get(balls.indexOf(ball)).direction = !balls.get(balls.indexOf(ball)).direction;44 ball.direction = !ball.direction;45 }46 tempBalls.add(ball);47 }48 balls=tempBalls;49 50 }51 Collections.sort(balls, (Ball x, Ball y) -> {52 return x.position - y.position;53 });54 String s = "";55 for (Ball ball : balls) {56 s += ball.position + " ";57 }58 System.out.print(s.substring(0, s.length() - 1));59 60 }61 62 static class Ball {63 // 小球运动方向 true 为向右64 boolean direction;65 // 小球位置66 int position;67 68 public Ball(boolean fangxiang, int weizhi) {69 super();70 this.direction = fangxiang;71 this.position = weizhi;72 }73 74 @Override75 public boolean equals(Object obj) {76 Ball o = null;77 if (obj instanceof Ball) {78 o = (Ball) obj;79 } else {80 return false;81 }82 return o.position == this.position;83 }84 85 }86 87 }