Jump to content

Exercicio Uri 1435 (Time limit exceeded)


Renan Alves

Postagens Recomendadas

Olá meus amigos, sou novo no fórum e estou com uma duvida muito grande em um exercício do https://www.beecrowd.com.br/, o que acontece, estou a quase uma semana tentando esse código com matrizes e mesmo assim não consigo passar pelo exercício, sempre dá erro de tempo limite excedido!

Já fiz o código funcionar com milhões de formas diferentes, mas o uri nunca aceita.

Já fiz com uma gambiarra indescritível  de if e else, e o exercício foi aceito, porém... quando tento mudar  para matriz o código não sempre da erro de tempo.

O exercício em questão é 1435:

Write a program that read an integer number N (0 ≤ N ≤ 100) that correspond to the order of a Bidimentional array of integers, and build the Array according to the above example.

Input

The input consists of several integers numbers, one per line, corresponding to orders from arrays to be built. The end of input is indicated by zero (0).

Output

For each integer number of input, print the corresponding array according to the example. (the values of the arrays must be formatted in a field of size 3 right justified and separated by a space. None space must be printed after the last character of each row of the array. A blank line must be printed after each array.

Em anexo coloquei como deve ser lido o código no console.

E esse é meu código:

import java.util.Scanner;

import java.text.DecimalFormat;

 

public class exercicio_matriz1435 {

 

public static void main(String[] args) {

DecimalFormat cs = new DecimalFormat("0.0");

Scanner sc = new Scanner(System.in);

 

int n;

 

while ((n = sc.nextInt()) != 0) {

int[][] mat = new int[n][n];

int x = n / 2;

if(n % 2 == 1) {

x++;

}

int a = 0, b = n - 1;

for(int l = 1; l <= x; l++) {

for(int i = a; i <= b; i++) {

for(int j = a; j <= b; j++) {

mat[i][j] = l;

}

}

a++;

b--;

}

for (int i = 0; i < mat.length; i++) {

for (int j = 0; j < mat[i].length; j++) {

if (j == 0) {

System.out.printf("%3d", mat[i][j]);

}

else {

System.out.printf(" %3d", mat[i][j]);

}

}

System.out.println();

}

System.out.println();

}

 

sc.close();

}

 

}

 

Esse é o erro apresentado:

 

PROBLEM:

1435 - Square Matrix I

ANSWER:

Time limit exceeded

LANGUAGE:

Java 14 (OpenJDK 1.14.0) [+2s]

RUNTIME:

4.000s

FILE SIZE:

905 Bytes

 

Por favor, alguém pode me ajudar? Pq coloquei na cabeça que só vou voltar a estudar java, quando eu terminar a página(5) de exercícios 100%, 

imagem_2024-01-11_011309428.png

Link to comment
Compartilhe em outros sites

  • 4 weeks later...
7 minutos atrás, Rogerio Santos disse:

Boa tarde, você pode encontrar a solução aqui 

 

Olá, boa noite!

 

Eu sei fazer desse jeito. Mas eu queria fazer ele com a matriz explicita! Então,  conseguir fazer o código funcionar dessa maneira.

Até agradeço por me responder! 

 

esse é o código que eu fiz:

import java.util.Scanner;

 

public class exercicio_matriz1435 {

 

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);

 

        int n;

 

        while ((n = sc.nextInt()) != 0) {

            int[][] mat = new int[n][n];

 

            int x = (n + 1) / 2;

            int a = 0, b = n - 1;

 

            for (int l = 1; l <= x; l++) {

                for (int i = a; i <= b; i++) {

                    for (int j = a; j <= b; j++) {

                        mat[i][j] = l;

                    }

                }

                a++;

                b--;

            }

 

            printMatrix(mat);

        }

 

        sc.close();

    }

 

    private static void printMatrix(int[][] matrix) {

        StringBuilder sb = new StringBuilder();

 

        for (int[] mat : matrix) {

            for (int j = 0; j < mat.length; j++) {

                if (j == 0) {

                    sb.append(String.format("%3d", mat[j]));

                }

                else {

                    sb.append(String.format(" %3d", mat[j]));

                }

            }

            sb.append("\n");

        }

 

        System.out.println(sb.toString());

    }

}

 

nisso consegui diminuir o tempo de resposta e fazer o processamento de acordo com o que era pedido.

Editado por Renan Alves
  • Curtir 1
Link to comment
Compartilhe em outros sites

1 hora atrás, Rogerio Santos disse:

Muito bom testei da maneira que passou e realmente eliminou o time exceed e foi aprovado

É porque o StringBuilder, faz uma concatenação entre todas as informações aplicadas. 

Demorou um tempo, mas deu certo! hahaha

  • Curtir 1
Link to comment
Compartilhe em outros sites

Crie uma conta ou entre para comentar 😀

Você precisa ser um membro para deixar um comentário.

Crie a sua conta

Participe da nossa comunidade, crie sua conta.
É bem rápido!

Criar minha conta agora

Entrar

Você já tem uma conta?
Faça o login agora.

Entrar agora


×
×
  • Create New...