碰撞的小球
问题描述
数轴上有一条长度为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为偶数。
保证所有小球的初始位置互不相同且均为偶数。
import java.util.Scanner;
class Main
{
public static void main(String[] args)
{
Ball[] ball;
Scanner sc=new Scanner(System.in);
int N=sc.nextInt();
int L=sc.nextInt();
int T=sc.nextInt();
ball=new Ball[N];
Main m=new Main();
for(int i=0;i<N;i++)
{
ball[i]=new Ball(1,sc.nextInt());
}
m.Start(ball, N, L, T);
for(Ball b:ball)
{
System.out.print(b.dir+" ");
}
}
public void Start(Ball[] ball,int N,int L,int T)//本题无序输入加大了循环遍历的次数
{
int time=0;
while(++time<=T)//按秒进行循环并记录每秒球的位置及方向改变信息
{
for(int i=0;i<N;i++)//修改球的位置信息以及边缘球方向更改信息
{
ball[i].dir+=ball[i].pos;
if(ball[i].dir==L)
ball[i].pos*=-1;
else if(ball[i].dir==0)
ball[i].pos*=-1;
}
for(int i=0;i<N-1;i++)
{
for(int j=i+1;j<N;j++)
{
if(ball[i].dir==ball[j].dir)//双重遍历两球是否相同位置以判断碰撞并更改方向信息
{
ball[i].pos*=-1;
ball[j].pos*=-1;
}
}
}
}
}
}
class Ball//存储球的信息
{
public int pos;//方向(1,-1)
public int dir;//位置
public Ball(int pos,int dir)
{
this.pos=pos;
this.dir=dir;
}
}
方法更新:以下方法采用纯数组。
思路:采用一维数组进行数据存储。小球运动方向的判别依赖于位置前的正负号,正数则表明小球将向右运动,负数则表明小球将向左运动。两个小球之间的位置比较以及输出则取位置的绝对值。
import java.util.Scanner;
public class Main {
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[] location=new int[n];
for (int i=0;i<n;i++)
{
location[i]=sc.nextInt();//存储球的初始位置
}
for (int i=0;i<t;i++)
{
for (int x=0;x<n-1;x++)//遍历查询是否存在位置相同的小球,存在则两球位置取反
for (int y=x+1;y<n;y++)
{
if (Math.abs(location[x]) == Math.abs(location[y])) {
location[x] = -location[x];
location[y] = -location[y];
}
}
for (int x=0;x<n;x++)
{
if (location[x] == L)//将已经到达边界的小球位置取反
location[x] = -L;
location[x]++;
}
}
for (int re:location)
{
System.out.print(Math.abs(re)+" ");
}
}
}