The second question of the 13th CCF certification
- It means that there are several small balls on a line, each moving in a certain direction at the same speed
- Reverse after collision
- At most, there will be two small balls colliding at the same time. I won't talk about it if there's proof
- Ask the position of all the balls at a certain time
Code:
import java.util.Scanner;
public class second
{
public static void main(String[] args)
{
Scanner scanner=new Scanner(System.in);
String string=scanner.nextLine();
String sd[]=string.split(" ");
int sum[]=transfer(sd);
int ball_number=sum[0];
int linelength=sum[1];
int time=sum[2];
String strball=scanner.nextLine();
int balls[]=transfer(strball.split(" "));
//deal
int position[]=new int [ball_number];
int direction[]=new int [ball_number];
boolean bian[]=new boolean[ball_number];
for (int i = 0; i < bian.length; i++) {
bian[i]=false;
}
//direction
for (int i = 0; i < direction.length; i++) {
direction[i]=1;
}
//position
for (int i = 0; i < position.length; i++) {
position[i]=balls[i];
}
int now=0;
while(now<time){
now++;
// A new round can change
for (int i = 0; i < bian.length; i++) {
bian[i]=false;
}
for (int i = 0; i < position.length; i++) {
//Disguised form
if (position[i]==linelength||position[i]==0) {
// System.out.println("hit the wall" + position[i]);
direction[i]=-direction[i];
}
//Colliding in disguise
for (int j = 0; j < direction.length; j++) {
if (!bian[j]&&i!=j&&position[i]==position[j]){
// System.out.println("Main.main()"+position[i]+position[j]);
direction[i]=-direction[i];
direction[j]=-direction[j];
bian[j]=true;
bian[i]=true;
}
}
}
for (int i = 0; i < position.length; i++) {
position[i]+=direction[i];
}
}
out(position);
}
static void out (int a[]){
for (int i = 0; i < a.length; i++) {
System.out.print(a[i]+" ");
}
System.out.println();
}
static int[] transfer(String str[]){
int a[]=new int [str.length];
for (int i = 0; i < str.length; i++) {
a[i]=Integer.parseInt(str[i]);
}
return a;
}
}
The thought code has given almost, the final result is also correct, I hope to help you.
Use a while loop to record the state of all the balls in every second, and then get the state of all the balls in t second step by step.