AcWing 3258. 碰撞的小球 Java 简单易懂
原题链接
简单
作者:
西红柿炒番茄_7
,
2024-11-28 18:49:15
,
所有人可见
,
阅读 1
Java 代码
package org.example.Test_13;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Scanner;
public class CollidingBalls {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int n = sc.nextInt();
int L = sc.nextInt();
int t = sc.nextInt();
int temp = 1;
ArrayList<Ball> balls = new ArrayList<>();
for (int i = 0; i < n; i++) {
int p = sc.nextInt();
Ball ball = new Ball(temp++, p);
balls.add(ball);
}
while (t-- > 0) {
// 遍历所有求的运动
// 0、先运动
// 1、两球碰撞 双循环
// 2、边缘碰撞
for (int i = 0; i < n; i++) {
Ball ball = balls.get(i);
if (ball.pos == 0 ||ball.pos == L){
ball.direction = !ball.direction;
}
if (ball.direction) {
ball.pos++;
} else {
ball.pos--;
}
}
for (int i = 0; i < n; i++) {
for (int j = i + 1; j < n; j++) {
Ball ball1 = balls.get(i);
Ball ball2 = balls.get(j);
if (ball1.pos == ball2.pos){
ball1.direction = !ball1.direction;
ball2.direction = !ball2.direction;
}
}
}
}
for (Ball ball : balls) {
System.out.print(ball.pos+" ");
}
}
static class Ball {
int id;
boolean direction = true;
int pos;
Ball(int id, int pos) {
this.id = id;
this.pos = pos;
}
}
}