Untitled
unknown
plain_text
a year ago
3.2 kB
12
Indexable
import java.util.Scanner;
import java.util.Arrays;
public class Main {
static int[] working;
static int[] operations;
static int answer = Integer.MAX_VALUE;
static int n, m, o;
static int eval(int prev, int curr, int op) {
if (prev == -10000000) {
return curr;
}
switch (op) {
case 1:
return prev + curr;
case 2:
return prev - curr;
case 3:
return prev * curr;
case 4:
if (curr == 0) {
return -1;
} else {
return prev / curr;
}
default:
return 0;
}
}
static boolean isDone(int prev, int curr, int Operation, int target) {
if (Operation == 4 && curr == 0) {
return false;
}
return eval(prev, curr, Operation) == target;
}
static void findMinTouch(int prev, int curr, int ooperation, int tou, int t) {
if (ooperation != -1 && curr != -10000000) {
boolean k = isDone(prev, curr, ooperation, t);
if (k && tou < o) {
if (answer > tou + 1) {
answer = tou + 1;
}
}
}
if (prev == t && tou < o && ooperation != -1 && curr == -10000000) {
answer = Math.min(answer, tou);
}
if (ooperation == -1 && curr == t && tou < o) {
answer = Math.min(answer, tou);
}
if (tou > o) return;
for (int i = 0; i < m; i++) {
if (curr == -10000000) break;
if (curr == 0 && ooperation == 4) continue;
int val = eval(prev, curr, ooperation);
findMinTouch(val, -10000000, operations[i], tou + 1, t);
}
for (int i = 0; i < n; i++) {
if (curr == -10000000) {
findMinTouch(prev, working[i], ooperation, tou + 1, t);
} else {
int val = Math.abs(curr);
val = val * 10 + working[i];
if (curr < 0) {
val *= -1;
}
findMinTouch(prev, val, ooperation, tou + 1, t);
}
}
}
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int t = sc.nextInt();
int count = 0;
while (t-- > 0) {
answer = Integer.MAX_VALUE;
n = sc.nextInt();
m = sc.nextInt();
o = sc.nextInt();
working = new int[n];
for (int i = 0; i < n; i++) {
working[i] = sc.nextInt();
}
operations = new int[m];
for (int i = 0; i < m; i++) {
operations[i] = sc.nextInt();
}
int target = sc.nextInt();
findMinTouch(-10000000, -10000000, -1, 0, target);
count++;
System.out.println("#" + count + ": " + answer);
}
sc.close();
}
}
Editor is loading...
Leave a Comment