封裝小球對象,屬性包括位置,方向(向右爲1,向左爲-1)。移動時pos += dir 就可以了;轉換方向就是 dir *= -1。記得在小球到達繩子邊界和與其他小球位置相同時要轉向。
奉上java滿分代碼
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;
public class Main{
private static int l;
static class Ball{
public int pos;
public int dir;
public Ball(int pos) {
this.pos = pos;
this.dir = 1;
}
public void move(){
this.pos += dir;
if(this.pos >= l || this.pos <= 0)
this.turn();
}
public void turn(){
this.dir *= -1;
}
}
public static void main(String[] args){
Scanner scanner = new Scanner(System.in);
String[] firstLine = scanner.nextLine().split(" ");
int n = Integer.parseInt(firstLine[0]);
l = Integer.parseInt(firstLine[1]);
int t = Integer.parseInt(firstLine[2]);
String[] secondLine = scanner.nextLine().split(" ");
List<Ball> balls = new ArrayList<>();
for(int i = 0; i < n; i++){
int pos = Integer.parseInt(secondLine[i]);
balls.add(new Ball(pos));
}
scanner.close();
while (t > 0){
for(Ball ball : balls)
ball.move();
for(Ball ballI : balls){
for(Ball ballJ : balls){
if(ballI.equals(ballJ))
continue;
if(ballI.pos == ballJ.pos)
ballI.turn();
}
}
t--;
}
for(Ball ball : balls){
System.out.print(ball.pos + " ");
}
}
}