fork download
  1. import java.util.*;
  2.  
  3. class OptimizedShootingGame {
  4. public static void main(String[] args) {
  5. Scanner sc = new Scanner(System.in);
  6. int t = sc.nextInt(); // number of test cases
  7.  
  8. while (t-- > 0) {
  9. int n = sc.nextInt(); // number of rows
  10. int m = sc.nextInt(); // number of columns
  11.  
  12. int[][] mat = new int[n][m]; // matrix to store the shooting board
  13. List<Integer> AarsiRows = new ArrayList<>();
  14. List<Integer> AarsiCols = new ArrayList<>();
  15. List<Integer> KryptoRows = new ArrayList<>();
  16. List<Integer> KryptoCols = new ArrayList<>();
  17.  
  18. // Read the matrix and store Aarsi's and Krypto's shot positions
  19. for (int i = 0; i < n; i++) {
  20. for (int j = 0; j < m; j++) {
  21. mat[i][j] = sc.nextInt();
  22. if (mat[i][j] == 1 || mat[i][j] == 3) {
  23. AarsiRows.add(i);
  24. AarsiCols.add(j);
  25. }
  26. if (mat[i][j] == 2 || mat[i][j] == 3) {
  27. KryptoRows.add(i);
  28. KryptoCols.add(j);
  29. }
  30. }
  31. }
  32.  
  33. // Sort the rows and columns of the shots
  34. Collections.sort(AarsiRows);
  35. Collections.sort(AarsiCols);
  36. Collections.sort(KryptoRows);
  37. Collections.sort(KryptoCols);
  38.  
  39. // Create result matrix to store final absolute differences
  40. int[][] res = new int[n][m];
  41.  
  42. // Calculate the result for each bullseye (i, j)
  43. for (int i = 0; i < n; i++) {
  44. for (int j = 0; j < m; j++) {
  45. int Aarsisum = calculateDistance(AarsiRows, i) + calculateDistance(AarsiCols, j);
  46. int Krysum = calculateDistance(KryptoRows, i) + calculateDistance(KryptoCols, j);
  47. res[i][j] = Math.abs(Aarsisum - Krysum);
  48. System.out.print(res[i][j] + " ");
  49. }
  50. System.out.println();
  51. }
  52. }
  53. }
  54.  
  55. // Function to calculate prefix sum distance for a given axis (rows or columns)
  56. static int calculateDistance(List<Integer> shots, int bullseye) {
  57. int total = 0;
  58. for (int shot : shots) {
  59. total += Math.abs(shot - bullseye);
  60. }
  61. return total;
  62. }
  63. }
  64.  
Success #stdin #stdout 0.13s 59032KB
stdin
2
1 5
2 1 3 0 1
1 8
1 1 3 0 2 0 3 3
stdout
5 2 1 0 1 
3 2 1 4 7 8 9 10