题目名称:小球游戏
某台有10个小球的游戏机,其设定的规则如下:
每一轮游戏在开始之前会把编号为0到9的小球依次放入从左到右编号也为0到9的10个位置;游戏开始后会快速对调任意两个球的位置若干次,并在结束时要求观众写出从左到右的小球编号顺序,写对就得奖。由于速度很快,所以直接靠观看写对很难。但有个程序员发现这台游戏机其实有一个固定的长度为n的操作序列数据库,每一轮游戏都是随机取一个起始操作序列编号和一个结束操作序列编号(操作序列编号从1到n)并从起始到结束依次执行每个操作序列编号对应的操作,而每个操作序列编号对应的操作就是对该次操作指定的两个编号的位置上的小球进行对调。现在给出操作序列数据库和每一轮游戏的起始操作序列编号和结束操作序列编号,求每轮游戏结束时从左到右的小球编号顺序。
输入描述:
第一行两个正整数n和m,表示操作序列的长度和游戏轮数。接下来n行,每行两个非负整数a和b,表示每个操作序列指定对调的两个小球所在位置的编号接下来m行每行两个正整数c和d表示该轮游戏中的起始操作序列编号和结束操作序列编号(c和d都是从1到h之间的正整数且c<d)
输出描述:
m行代表每轮游戏结束时的小球编号顺序
输入示例:
1 2 3 4 5 6 7 8 9
| 5 3 0 1 1 2 2 3 0 1 9 0 3 3 1 5 3 4
|
输出示例:
1 2 3
| 0 1 3 2 4 5 6 7 8 9 9 1 3 0 4 5 6 7 8 2 1 0 3 2 4 5 6 7 8 9
|
代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49
| import java.util.Scanner;
public class BallGame { public static void main(String[] args) { Scanner scanner = new Scanner(System.in); int n = scanner.nextInt(); int m = scanner.nextInt();
int[][] operations = new int[n][2]; for (int i = 0; i < n; i++) { operations[i][0] = scanner.nextInt(); operations[i][1] = scanner.nextInt(); }
int[][] games = new int[m][2]; for (int i = 0; i < m; i++) { games[i][0] = scanner.nextInt(); games[i][1] = scanner.nextInt(); }
int[][] balls = new int[m][10];
for (int i = 0; i < m; i++) { int[] sequence = new int[10]; for (int j = 0; j < 10; j++) { sequence[j] = j; }
for (int j = games[i][0] - 1; j < games[i][1]; j++) { swap(sequence, operations[j][0], operations[j][1]); }
balls[i] = sequence; }
for (int i = 0; i < m; i++) { for (int j = 0; j < 10; j++) { System.out.print(balls[i][j] + " "); } System.out.println(); } }
private static void swap(int[] array, int pos1, int pos2) { int temp = array[pos1]; array[pos1] = array[pos2]; array[pos2] = temp; } }
|