(UVA) Matrix Transpose - Solution

Link to the problem: https://uva.onlinejudge.org/index.php?option=com_onlinejudge&Itemid=8&category=24&page=show_problem&problem=1836

We only need to transpose the given matrix and to handle the output as requested.


import java.io.*;
import java.util.*;

class Main {
    public void process() throws NumberFormatException, IOException {
        Scanner sc = new Scanner(System.in);
        
        while (sc.hasNext()) {
            int numRows = sc.nextInt();
            int numCols = sc.nextInt();
            int[][] matrix = new int[numRows+1][numCols+1];
            for (int i = 1; i <= numRows; i++) {
                int numNotZero = sc.nextInt();
                int[] notZero = new int[numNotZero];
                for (int j = 0; j < numNotZero; j++) {
                    notZero[j] = sc.nextInt();
                }
                for (int j = 0; j < numNotZero; j++) {
                    matrix[i][notZero[j]] = sc.nextInt();
                }
            }
            
            int numRowsT = numCols;
            int numColsT = numRows;
            int[] numNotZeroT = new int[numRowsT+1];
            ArrayList<ArrayList<Integer>> colsNotZero = new ArrayList<>();
            for (int i = 0; i <= numCols; i++) {
                colsNotZero.add(new ArrayList<Integer>());
            }
            int[][] transpose = new int[numRowsT+1][numColsT+1];
            for (int i = 1; i <= numCols; i++) {
                for (int j = 1; j <= numRows; j++) {
                    transpose[i][j] = matrix[j][i];
                    if (transpose[i][j] != 0) {
                        numNotZeroT[i]++;
                        colsNotZero.get(i).add(j);
                    }
                }
            }
            
            System.out.println(numRowsT + " " + numColsT);
            for (int i = 1; i <= numRowsT; i++) {
                System.out.print(numNotZeroT[i]);
                for (int j = 0; j < colsNotZero.get(i).size(); j++) {
                    System.out.print(" " + colsNotZero.get(i).get(j));
                }
                System.out.println();
                for (int j = 0; j < colsNotZero.get(i).size(); j++) {
                    if (j == colsNotZero.get(i).size()-1) {
                        System.out.print(transpose[i][colsNotZero.get(i).get(j)]);
                        break;
                    }
                    System.out.print(transpose[i][colsNotZero.get(i).get(j)] + " ");
                }
                System.out.println();
            }
        }
    }
    
    public static void main(String[] args) throws NumberFormatException, IOException {
        Main m = new Main();
        m.process();
        
        System.exit(0);
    }
}

Comments

Popular posts from this blog

(Coderbyte) Dash Insert II - Solução

(Coderbyte) Run Length - Solução

(Coderbyte) Counting Minutes I - Solução