Algorithm
Problem Name: 2 AD-HOC - beecrowd | 1578
Problem Link: https://www.beecrowd.com.br/judge/en/problems/view/1578
Matrix of Squares
By Leandro Zatesko, UFFS Brazil
Timelimit: 1
Atrapalhilton is a student very dedicated, though very, very clumsky. Last week, his Math teacher, Mr. Sabetudilton, recommended the class a list of exercises about matrices. Atrapalhilton, diligent as he is, decided to make the exercises at the very same day, as soon he arrived home, though only after watching the evening episode of The Striped Little Hen, his favorite TV show. In the statement of one of the exercises it could be read:
- Calculate the square of each one of the matrices below…
However, Atrpalhilton made a huge mass. For him, the square of a square matrix A is the matrix of the squares of the values of matrix A. For example, the square of matrix
1 | 3 |
5 | 7 |
is not for him,
16 | 24 |
40 | 64 |
but
1 | 9 |
25 | 49 |
Atrapalhilton got to calculate the “square” of the first, the second and the third matrices and realised that it was already too late, that he wouldn't be able to finish calculating the “squares” of all N matrices of the list. Hence, he decided to write a program which would do the job for him.
Input
The first line of the input consists of a single positive integer N (N ≤ 100), which stands for the number of matrices whose “squares” have not been calculated yet. Follow the description of each one of the N matrices. The first line of the description of a matrix consists of a single integer M (1 ≤ M ≤ 20), which represents the number of lines and the number of columns of the matrix. Follow, then, M lines, each one of M integers aij (0 ≤ aij ≤ 232-1, 1 ≤ i,j ≤ M), which correspond to the cells of the matrix, in a way such that consecutive values in a same line are separated by a blank space.
Output
Print the “square” of each matrix of the input, according to the meaning of the “square” of a matrix to Atrapalhilton. Before printing each “square”, print the line “Quadrado da matriz #x:” (without the quotation marks), in order to help Atrapalhilton not to get lost while writing out the results to the notebook. Start the counting in x = 4, after all, Atrapalhilton has already calculated the “squares” of the first 3 matrices. Add as much blank spaces as needed to the left of each value in order to get the values of a same column altogether flush right, so that there is a blank space in addition to the mandatory blank space which separates consecutive columns. Print also a blank line between two consecutive “squares” of matrices.
Sample Input | Sample Output |
1 |
Quadrado da matriz #4: |
Code Examples
#1 Code Example with C Programming
Code -
C Programming
#include <stdio.h>
#include <math.h>
int main (void)
{
unsigned short casos, qtsCaso = 4, ordem;
unsigned short linha, coluna, qtsDigitosAtual, k;
long double maior;
scanf("%hu", &casos);
while (casos--)
{
scanf("%hu", &ordem);
long double matriz[ordem][ordem];
// Preenche a matriz e já faz o quadrado do termo;
for (linha = 0; linha < ordem; linha++)
for (coluna = 0; coluna < ordem; coluna++)
{
scanf("%Lf", &matriz[linha][coluna]);
matriz[linha][coluna] *= matriz[linha][coluna];
}
printf("Quadrado da matriz #%hu:\n", qtsCaso);
for (linha = 0; linha < ordem; linha++)
{
for (coluna = 0; coluna < ordem; coluna++)
{
maior = 0;
// Acha o maior elemento da coluna;
for (k = 0; k < ordem; k++)
if (matriz[k][coluna] > maior)
maior = matriz[k][coluna];
// O recuo no printf é em termos do maior elemento da coluna;
// Ou seja, todos os elementos da coluna estão justificados
// de acordo com o número que tem a maior quantidade de dígitos
// nessa mesma coluna;
// log na base 10 nos da a quantidade de digitos de um número;
qtsDigitosAtual = ((floor(log10(maior))) + 1);
// Tive muitos problemas por causa disso;
// Não pode haver espaços após o último elemento na coluna!
if (coluna != ordem && coluna != 0)
printf(" ");
// flag '*' antes da diretiva de formatação nos dá um recuo dinâmico
// Na impressão;
printf("%*.Lf", qtsDigitosAtual, matriz[linha][coluna]);
}
printf("\n");
}
qtsCaso++;
// Quebra de linha condicional para não imprimir caso seja a última matriz;
if (casos != 0)
printf("\n");
}
}
Copy The Code &
Try With Live Editor
Input
2
7 12
1024 1
Output
49 144
1048576 1
#2 Code Example with C++ Programming
Code -
C++ Programming
#include <cmath>
#include <iomanip>
#include <iostream>
using namespace std;
typedef unsigned long long llu;
#define endl '\n'
#define MAXN 25
#define max(A, B) (A > B) ? (A) : (B)
int main() {
ios_base::sync_with_stdio(0);
cin.tie(0);
int casos;
cin >> casos;
for (int davez = 4; davez < casos + 4; davez++) {
if (davez != 4) cout << endl;
int ordem;
cin >> ordem;
cout << "Quadrado da matriz #" << davez << ":\n";
llu matriz[MAXN][MAXN], digitos[MAXN];
for (int i = 0; i < ordem; i++) digitos[i] = 1LL;
for (int i = 0; i < ordem; i++) {
for (int j = 0; j < ordem; j++) {
cin >> matriz[i][j];
matriz[i][j] *= matriz[i][j];
if (matriz[i][j])
digitos[j] = max(digitos[j], llu(log10(matriz[i][j])) + 1);
}
}
for (int i = 0; i < ordem; i++) {
for (int j = 0; j < ordem; j++) {
if (j == 0)
cout << setw(digitos[j]) << matriz[i][j];
else
cout << " " << setw(digitos[j]) << matriz[i][j];
}
cout << endl;
}
}
return 0;
}
Copy The Code &
Try With Live Editor
Input
2
7 12
1024 1
Output
49 144
1048576 1
#3 Code Example with Javascript Programming
Code -
Javascript Programming
const { readFileSync } = require("fs")
const [[numCases], ...lines] = readFileSync("/dev/stdin", "utf8")
.split("\n")
.map(line => line.split(" ").map(value => Number.parseInt(value, 10)))
const input = (function* (lines) {
for (const line of lines) yield line
})(lines)
const Num = {
square(num = 0) {
if (Math.log2(num) > 26.5) return BigInt(num) ** 2n
else return Math.pow(num, 2)
}
}
/** @param { any[][] } matrix */
function alignFromRigthByColumns(matrix) {
const paddingsSize = new Array(matrix.length).fill(0)
const columnPlaceholderArray = new Array(matrix.length).fill(0)
for (let col = 0; col < matrix.length; col++) {
const columnLens = columnPlaceholderArray.map((_, row) => `${matrix[row][col]}`.length)
const biggestNumLengthForThisColumn = Reflect.apply(Math.max, null, columnLens)
paddingsSize[col] = biggestNumLengthForThisColumn
}
for (let row = 0; row < matrix.length; row++) {
for (let col = 0; col < matrix.length; col++) {
matrix[row][col] = String(matrix[row][col]).padStart(paddingsSize[col], " ")
}
}
return matrix
}
function main() {
const responses = []
for (let index = 0; index < numCases; index++) {
const matrixSize = input.next().value[0]
const squareMatrix = Array.from({ length: matrixSize }, () => (input.next().value || [0]).map(Num.square))
const alignedColumns = alignFromRigthByColumns(squareMatrix).map(row => row.join(" ")).join("\n")
responses.push(`Quadrado da matriz #${index + 4}:\n${alignedColumns}`)
}
console.log(responses.join("\n\n"))
}
main()
Copy The Code &
Try With Live Editor
Input
2
7 12
1024 1
Output
49 144
1048576 1
#4 Code Example with Python Programming
Code -
Python Programming
def imp(n, e):
print(' ' * (e - len(str(n))), end='')
print(n, end='')
return
c = 4
for g in range(int(input())):
n = int(input())
v = []
for i in range(n):
t = [int(x)**2 for x in str(input()).split()]
v.append(t)
if c != 4: print()
print('Quadrado da matriz #{}:'.format(c))
c += 1
esp = []
for i in range(n):
m = 0
for j in range(n):
if len(str(v[j][i])) > m: m = len(str(v[j][i]))
esp.append(m)
for i in range(n):
for j in range(n):
imp(v[i][j], esp[j])
if j != n-1: print(end=' ')
print()
Copy The Code &
Try With Live Editor
Input
2
7 12
1024 1
Output
49 144
1048576 1