(URI) Apagando e Ganhando - Solution
Link to the problem: https://www.urionlinejudge.com.br/judge/pt/problems/view/1084
For this problem, it is necessary to use a stack, which will enable us to discard and keep the numbers.
import java.io.*;
import java.util.*;
class Main {
public static int reader(BufferedReader br) throws NumberFormatException, IOException {
int n;
int resp = 0;
while (true) {
n = br.read();
if (n >= '0' && n <= '9') {
break;
}
}
while (true) {
resp = resp*10 + n-'0';
n = br.read();
if (n < '0' || n > '9') {
break;
}
}
return resp;
}
public static void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numDigits = reader(br);
int numDigitsErase = reader(br);
while (numDigits != 0 || numDigitsErase != 0) {
String number = br.readLine();
int countDigitsErased = 0;
Deque<Integer> stack = new ArrayDeque<Integer>();
for (int i = 0; i < numDigits; i++) {
int digit = number.charAt(i)-'0';
while (stack.size() > 0 && digit > stack.peekFirst() && countDigitsErased < numDigitsErase) {
stack.pollFirst();
countDigitsErased++;
}
stack.addFirst(digit);
}
for (int i = countDigitsErased; i < numDigitsErase; i++) {
stack.pollFirst();
}
while (stack.size() > 0) {
System.out.print(stack.pollLast());
}
System.out.println();
numDigits = reader(br);
numDigitsErase = reader(br);
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
For this problem, it is necessary to use a stack, which will enable us to discard and keep the numbers.
import java.io.*;
import java.util.*;
class Main {
public static int reader(BufferedReader br) throws NumberFormatException, IOException {
int n;
int resp = 0;
while (true) {
n = br.read();
if (n >= '0' && n <= '9') {
break;
}
}
while (true) {
resp = resp*10 + n-'0';
n = br.read();
if (n < '0' || n > '9') {
break;
}
}
return resp;
}
public static void process() throws NumberFormatException, IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
int numDigits = reader(br);
int numDigitsErase = reader(br);
while (numDigits != 0 || numDigitsErase != 0) {
String number = br.readLine();
int countDigitsErased = 0;
Deque<Integer> stack = new ArrayDeque<Integer>();
for (int i = 0; i < numDigits; i++) {
int digit = number.charAt(i)-'0';
while (stack.size() > 0 && digit > stack.peekFirst() && countDigitsErased < numDigitsErase) {
stack.pollFirst();
countDigitsErased++;
}
stack.addFirst(digit);
}
for (int i = countDigitsErased; i < numDigitsErase; i++) {
stack.pollFirst();
}
while (stack.size() > 0) {
System.out.print(stack.pollLast());
}
System.out.println();
numDigits = reader(br);
numDigitsErase = reader(br);
}
return;
}
public static void main(String[] args) throws NumberFormatException, IOException {
Main m = new Main();
m.process();
System.exit(0);
}
}
Comments
Post a Comment