TOPIC
PROBLEM 1246 - URI Fórum 1.0
This topic was solved and cannot recieve new replies.
-
BugFree replied 9 years ago
Pessoal, alguem pode me ajuda, estou levando 40% WA, e tb me dizer porque no caso de teste 2 da 50 e não 40?
#include <stdio.h> #include <string.h> typedef struct TipoEstacionamento{ int placa; int comprimento; }TipoEstacionamento; typedef struct Limite { int Limite; }Limite; int main() { int Comp,Event,TamStruct; Limite Limite; while(scanf("%d %d",&Comp,&Event)!=EOF){ int Placa=0,Compri=0,Valor=0,i=0; char C; Valor=0; TamStruct=0; Limite.Limite=Comp; TipoEstacionamento Estacionamento[Event]; getchar(); for(i=0;i<Event;i++) { C=getchar(); if(C=='S') { int K=0; scanf("%d",&Placa); for(K=0;K<TamStruct;K++) { if(Placa == Estacionamento[K].placa) { Limite.Limite+=Estacionamento[K].comprimento; Estacionamento[K].comprimento=0; Estacionamento[K].placa=0; break; } } }else if(C=='C') { scanf("%d %d",&Estacionamento[TamStruct].placa,&Estacionamento[TamStruct].comprimento); if(Limite.Limite>=Estacionamento[TamStruct].comprimento) { Limite.Limite-=Estacionamento[TamStruct].comprimento; Valor+=10; //Zerar } TamStruct++; } getchar(); } printf("%d\n",Valor); } return(0); }
-
crbonilha replied on Oct 25 2013
Experimente fazer a leitura de dados de uma forma separada, tal como usar nextInt(), e nextChar(), uma vez que ler a linha completa envolve ter que formatar a entrada.
Em relação ao caso de teste, os eventos acontecem na seguinte ordem: Nos três primeiros eventos, chegam três carros ao estacionamento, cada um de comprimento 10, e cada um ocupa um pedaço do estacionamento. Em seguida, saem dois carros (o primeiro e o terceiro, como pode-se notar pela placa e ordem de chegada). Como o problema especifica que eles são estacionados no primeiro lugar possível, o único carro que restou está justamente no meio do estacionamento (que desperdício). Como consequência, o próximo carro que chega, de comprimento 20, não consegue estacionar (há duas vagas de tamanho 10, mas não uma de tamanho 20). Em seguida o carro do meio sai. Chega outro carro de tamanho 20. Esse mesmo carro então sai. E o último carro chega.
Temos um total de 5 carros, e 5 * 10 = 50.
-
bviana replied on Oct 22 2013
alguém poderia me explica porque a resposta dessa entrada:
30 10 C 1000 10 C 1001 10 C 1002 10 S 1000 S 1002 C 1003 20 S 1001 C 1004 20 S 1004 C 1005 30
É 50 e não 40
-
jdamasio0 replied 9 years ago
Oi, adriel.
Há problema sim em ler com scanner.next() ou nextInt(). O problema é que ele procura, de fato, o próximo inteiro (nextInt), e mesmo que depois venha um /n, ele vai dexá-lo lá, para ser lido na próxima leitura, pois de fato não faz parte do int. Sugiro você, e qualquer um que usa Java, sempre ler usando .nextLine(), e trabalhar em cima dela, quebrando a String com .split(" ") ou algo assim.
Abraços.
-
adinelli replied 9 years ago
*Update: O problema foi em outra parte do código! :D Eu estava usando a biblioteca / classe Arrays para converter uma array em ArrayList, aparentemente era isso que estava dando Possible Runtime Error (não entendi o porquê, entretanto).
boolean isCarInside = Arrays.asList(spaces).contains(car_id); <- removi esta implementação
O código está usando apenas array com loops for agora;
Pessoal, estou tendo problema para resolver, usando Java.
Minhas submissões dão Possible Runtime Error. Aparentemente, meu código precisa receber um Enter a mais para finalizar, entendo pelo enunciado que só deveria haver um Enter. No entanto, não conheço uma solução que leia desta forma.
No Eclipse, o resultado sai correto.
Desenvolvi dois exemplos, usando Scanner e BufferedReader (este NÃO é o código original, apenas a lógica com a qual eu leio os inputs).
Usando Scanner:
Scanner scan = new Scanner(System.in); Integer length, occurrences, car_id, size; char event; while(scan.hasNextInt()) { length = scan.nextInt(); System.out.println("This is the length: " + length); occurrences = scan.nextInt(); System.out.println("This is number of events: " + occurrences); for(int i = 1; i <= occurrences; i++) { event = scan.next().charAt(0); System.out.println("The event " + event); if(event == 'C') { car_id = scan.nextInt(); System.out.println("This is the car ID: " + car_id); size = scan.nextInt(); System.out.println("This is the car size: " + size); } else { car_id = scan.nextInt(); System.out.println("This is the car ID: " + car_id); } } } System.out.println("Im done!");
Usando BufferedReader:
BufferedReader reader = new BufferedReader(new InputStreamReader(System.in)); Integer length = 0, occurrences, car_id, size; char event; String line; String[] inputs; while((line = reader.readLine()) != null && !line.equals("")) { inputs = line.split(" "); length = Integer.parseInt(inputs[0]); System.out.println("This is the length: " + length); occurrences = Integer.parseInt(inputs[1]); System.out.println("This is number of events: " + occurrences); for(int i = 1; i <= occurrences; i++) { if ((line = reader.readLine()) != null && !line.equals("")) { inputs = line.split(" "); event = inputs[0].charAt(0); System.out.println("The event " + event); if(event == 'C') { car_id = Integer.parseInt(inputs[1]); System.out.println("This is the car ID: " + car_id); size = Integer.parseInt(inputs[2]); System.out.println("This is the car size: " + size); } else { car_id = Integer.parseInt(inputs[1]); System.out.println("This is the car ID: " + car_id); } } } } System.out.println("Im done!");
Há algo errado nessa maneira de receber os inputs? Ou pode ser qualquer outra coisa não relacionada?
-
Roberto0 replied 9 years ago
Olá, groth.
Muito obrigado!
Se por acaso alguém precisar de um caso de teste menor e que mostre onde meu problema estava, testem com:
10 6 C 1001 2 C 1002 2 C 1003 4 S 1002 C 1005 2 C 1006 2
Abraços.
-
ggroth replied 9 years ago
Tente as seguintes entradas:
200 100 C 1588 93 C 6287 24 S 6287 C 5517 43 S 1588 S 5517 C 4703 25 S 4703 C 5517 87 C 4458 14 S 5517 S 4458 C 5193 2 C 8869 43 S 8869 C 3452 46 C 5212 92 C 5517 2 S 3452 C 4703 52 S 5212 C 4458 50 S 4703 C 8869 16 S 5193 S 8869 S 4458 C 1723 64 S 5517 S 1723 C 5212 87 C 1233 24 S 5212 C 9391 50 S 1233 C 7056 2 C 4703 37 C 5212 42 C 3848 62 C 6287 68 S 3848 C 3452 82 S 7056 C 1723 93 C 3452 66 S 9391 C 3944 85 S 4703 S 5212 S 3452 C 4703 14 S 4703 C 3944 9 C 5212 44 S 5212 S 3944 C 1974 32 S 1974 C 3944 7 S 3944 C 5151 17 C 4458 73 S 5151 C 3848 44 S 3848 C 3452 88 S 4458 S 3452 C 5517 62 S 5517 C 9003 49 S 9003 C 1974 37 C 3944 52 C 1723 27 S 3944 C 1233 25 S 1233 S 1723 S 1974 C 5212 24 S 5212 C 5212 33 S 5212 C 9003 28 S 9003 C 3848 98 C 8869 66 C 5212 53 C 5517 74 C 4703 75 S 3848 C 3944 47 S 8869 C 1974 68 C 6287 2 C 5212 18 S 5212 C 3848 39 S 1974 200 100 C 7277 99 S 7277 C 7298 81 C 8545 75 C 8517 35 S 7298 S 8517 S 8545 C 4037 6 S 4037 C 6769 39 S 6769 C 7440 98 S 7440 C 7440 57 S 7440 C 7277 62 S 7277 C 7440 6 C 8032 79 S 8032 C 3725 22 S 3725 S 7440 C 8517 30 S 8517 C 8032 94 S 8032 C 2668 24 C 3725 32 S 3725 C 3725 65 S 3725 S 2668 C 1563 50 C 7440 13 C 5175 23 S 5175 S 7440 S 1563 C 1563 57 S 1563 C 7369 11 C 6769 72 S 7369 C 7369 53 S 6769 S 7369 C 8032 28 S 8032 C 7440 56 S 7440 C 6276 18 S 6276 C 7298 43 C 4037 27 S 4037 C 8846 38 C 4037 35 S 8846 S 7298 S 4037 C 7298 67 C 7369 3 S 7298 C 6276 18 C 2668 30 C 7298 80 S 2668 S 7298 C 2668 51 C 2647 3 C 7883 80 C 8388 84 C 7298 51 C 3725 59 S 2647 C 3725 77 C 8032 49 S 7369 C 7883 50 S 7298 S 2668 S 8032 C 5175 68 S 6276 C 2647 13 S 5175 S 2647 C 8609 19 S 8609 C 8846 99 S 8846 C 8517 75 S 8517 C 8609 95 S 8609 C 5175 56 S 5175 C 7277 91
A saída deveria ser
480 480
-
Roberto0 replied 9 years ago
Olá, pessoal.
Também estou encontrando problemas. Não sei em qual caso meu algoritmo não retorna a resposta correta. Estou conseguindo W.A. (50%). Alguém poderia me ajudar? Segue o código.
import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; import java.util.HashMap; public class Main { public static void main(String[] args) throws IOException { BufferedReader in = new BufferedReader(new InputStreamReader(System.in)); StringBuilder out = new StringBuilder(); String line; HashMap<String, Integer> indexes; int counter = 0; while ((line = in.readLine()) != null) { indexes = new HashMap<String, Integer>(); //System.out.println("Reading " + (++counter) + ", " + line + ".\n"); String input[] = line.split(" "); int C = Integer.parseInt(input[0]); int N = Integer.parseInt(input[1]); int park[] = new int[C]; int total = 0; for (int i=0; i<N; i++) { line = in.readLine(); input = line.split(" "); if (input[0].equals("C")) { int accumulated = 0; int length = Integer.parseInt(input[2]); //System.out.println("Trying to add " + input[1] + "."); for (int j=0; j<C; j++) { if (park[j] == 0) { accumulated++; if (accumulated == length) { //System.out.println("Found at " + j + "."); park[((j+1)-length)] = j+1; indexes.put(input[1], ((j+1)-length)); total += 10; //System.out.println("Added at position " + ((j+1)-length) + "."); //System.out.println("Value of park[" + ((j+1)-length) + "] = " + park[((j+1)-length)] + "."); } } else { accumulated = 0; j = (park[j]-1); } } } else { //System.out.println("Trying to remove " + input[1] + "."); if (indexes.containsKey(input[1])) { int index = indexes.get(input[1]); park[index] = 0; indexes.remove(input[1]); } } } out.append(total).append("\n"); } System.out.print(out.toString()); } }
Obrigado!
-
dpereira1 replied on Apr 11 2014
Estou recebendo "Possible Runtime Error" em vários problemas meus escritos em java, não só esse. Só que não to conseguindo encontrar o erro nos meus programas e quando eu clico em submissão, não informa nada sobre o erro. O arquivo não está em pacote, a classe está denominada Main. Não sei o que eu faço mais... submeti 5 soluções para esse e mais um problema e as 5 deram esse erro. O que posso fazer?
Poderiam me ajudar? :(
A estrutura dos meus programas seguem basicamente essa:
``` import java.io.BufferedReader; import java.io.IOException; import java.io.InputStreamReader; public class Main { public static void main(String[] args) throws IOException { InputStreamReader ir = new InputStreamReader(System.in); BufferedReader in = new BufferedReader(ir); StringBuilder sb = new StringBuilder(); String[] row; while (in.ready()) { row = in.readLine().split(" "); ... } } } ```
-
avmendes replied on Dec 13 2013
Aliás, acabei de submeter o mesmo código para o SPOJ e ele foi aceito!
-
avmendes replied on Dec 13 2013
Então galera, preciso de uma ajuda... Eu resolvi o problema, estou recebendo WA e não consigo entender o porque... Eu inclusive teste o .in e .out, já que o exercício foi da primeira fase da maratona de 2011, e todos os casos deram certo... Segue o meu código...
#include <iostream> using namespace std; int main() { int met, ev, prec; int plac, comp; char sit; int est[1001]; while(cin >> met >> ev) { for(int i = 0; i < met; i++) est[i] = 0; prec = 0; while(ev-- > 0) { cin >> sit; if(sit == 'C') { cin >> plac >> comp; int vazio = 0; for(int i = 0; i < met; i++) { if(est[i] == 0) vazio++; if(vazio == comp) { for(int k = i - comp + 1; k <= i; k++) est[k] = plac; prec += 10; break; } if(est[i] != 0) vazio = 0; } } else { bool f = false; cin >> plac; for(int i = 0; i < met; i++) { if(est[i] == plac) { est[i] = 0; f = true; } else if(f) break; } } } cout << prec << endl; } }
-
bviana replied on Oct 22 2013
To com um problema de Possible runtime error
Exception in thread "main" java.lang.StringIndexOutOfBoundsException: String index out of range: -1 at java.lang.String.substring(String.java:1911) at Main.main(Main.java:22)
BufferedReader br = new BufferedReader(new InputStreamReader(System.in)); String line = "" + br.readLine(); c = line.substring(0, line.indexOf(" ")); e = line.substring(line.indexOf(" ") + 1); comp = Integer.parseInt(c); eventos = Integer.parseInt(e);
nesse trecho de código e já to sem ideias. Agradeço desde já
-
crbonilha replied on May 12 2013
Uma coisa que sempre dá problema, sabe-se lá porque, é ler caracteres no scanf. Para evitar isso, eu sempre coloco um espaço entre as aspas, antes do %c, caso ele seja o primeiro. Por exemplo:
scanf(" %c", &caractere);
Outra coisa chata é fazer leitura com scanf e gets no mesmo código. Se não me engano o scanf as vezes deixa alguma "sujeira" no buffer e o gets acaba pegando ela, em vez da entrada que deveria pegar. Pra evitar isso, pode-se usar um getchar() logo após o scanf, caso planeje usar o gets no futuro. Por exemplo:
scanf("%d", &inteiro); getchar(); gets(entrada);
Experimenta essas mudanças, caso não de certo a gente tenta outra coisa.
-
Rafael0 replied on May 12 2013
Olá, estou usando um loop para ler a entrada, mas parece que esta sem fim e o sistema me retorna "Time limit exceeded".
Gostaria de dicas pra tratar esse loop corretamente.
No momento está assim:
gets(linha); while (sscanf(linha, "%d %d", &N, &p) != EOF) { ... for (i=0; i<p; i++) { gets(linha); sscanf(linha, "%c", &io); if (io == 'C') sscanf(linha, "%c %d %d", &io, &placa, &tamanho); else sscanf(linha, "%c %d", &io, &placa); ... } ... gets(linha); }
Obrigado.