-
Notifications
You must be signed in to change notification settings - Fork 0
/
UVA112.java
executable file
·81 lines (76 loc) · 2.63 KB
/
UVA112.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.Scanner;
class Main {
public static void main(String[] args) throws IOException {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
StringBuilder sb = new StringBuilder();
while (br.ready()) {
sb.append((char) br.read());
}
String brArbol = sb.toString();
Scanner scConvertir = new Scanner(brArbol);
while (scConvertir.hasNextInt()) {
long suma = scConvertir.nextInt();
String arbol = convertir(scConvertir);
if (existeSuma(new Scanner(arbol), suma, 0).equals("yes")) {
System.out.println("yes");
} else {
System.out.println("no");
}
}
}
private static String convertir(Scanner sc) {
StringBuilder sb = new StringBuilder();
int parentesisFaltantes = 0;
while (sc.hasNext()) {
String linea = sc.next();
sb.append(' ');
sb.append(linea);
parentesisFaltantes = parentesisFaltantes + parentActual(linea);
if(parentesisFaltantes == 0) break;
}
String arbol = sb.toString();
arbol = arbol.replace("(", " ( ");
arbol = arbol.replace(")", " ) ");
return arbol;
}
private static int parentActual(String linea) {
int parentesis = 0;
for (int i = 0; i < linea.length(); i++) {
char p = linea.charAt(i);
if (p == '(') {
parentesis++;
}
if (p == ')') {
parentesis--;
}
}
return parentesis;
}
private static String existeSuma(Scanner scArbol, long suma, long sumaActual) {
scArbol.next();
String numero = scArbol.next();
if (numero.equals(")")) {
return "noHijo";
} else {
int hijo = Integer.parseInt(numero);
sumaActual = sumaActual + hijo;
String hijoIzq = existeSuma(scArbol, suma, sumaActual);
if (hijoIzq.equals("yes")) {
return "yes";
}
String hijoDer = existeSuma(scArbol, suma, sumaActual);
if (hijoDer.equals("yes")) {
return "yes";
}
scArbol.next();
if (hijoIzq.equals("noHijo") && hijoDer.equals("noHijo") && suma == sumaActual) {
return "yes";
} else {
return "no";
}
}
}
}