Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.util.ArrayList;
- import java.util.HashMap;
- import java.util.Scanner;
- public class bunnies {
- public static void main(String[] args) {
- Scanner in = new Scanner(System.in);
- int T = in.nextInt();
- for (int t = 1; t <= T; t++) {
- int n = in.nextInt();
- int[] tmps = new int[n];
- int[] hums = new int[n];
- HashMap<Integer, ArrayList<Integer>> Phums = new HashMap<Integer, ArrayList<Integer>>();
- HashMap<Integer, ArrayList<Integer>> Nhums = new HashMap<Integer, ArrayList<Integer>>();
- for (int i = 0; i < n; i++) {
- tmps[i] = in.nextInt();
- }
- for (int i = 0; i < n; i++) {
- hums[i] = in.nextInt();
- }
- for (int i = 0; i < n; i++) {
- int pos = tmps[i] + hums[i];
- int neg = tmps[i] - hums[i];
- if (!Phums.containsKey(pos)) {
- Phums.put(pos, new ArrayList<Integer>());
- }
- Phums.get(pos).add(i);
- if (!Nhums.containsKey(neg)) {
- Nhums.put(neg, new ArrayList<Integer>());
- }
- Nhums.get(neg).add(i);
- }
- ArrayList<Integer> q = new ArrayList<Integer>();
- boolean[] visited = new boolean[n];
- q.add(0);
- visited[0] = true;
- int step;
- for (step = 0; q.size() > 0 && !visited[n - 1]; step++) {
- ArrayList<Integer> nq = new ArrayList<Integer>();
- while (q.size() > 0) {
- int ind = q.remove(q.size() - 1);
- int pos = tmps[ind] + hums[ind];
- int neg = tmps[ind] - hums[ind];
- if (Phums.containsKey(pos)) {
- for (int i : Phums.get(pos)) {
- if (!visited[i]) {
- visited[i] = true;
- nq.add(i);
- }
- }
- Phums.remove(pos);
- }
- if (Nhums.containsKey(neg)) {
- for (int i : Nhums.get(neg)) {
- if (!visited[i]) {
- visited[i] = true;
- nq.add(i);
- }
- }
- Nhums.remove(neg);
- }
- }
- q = nq;
- }
- if (!visited[n - 1]) {
- step = -1;
- }
- System.out.println("Field #" + t + ": " + step + "\n");
- }
- in.close();
- }
- public static void debug(Object o) {
- System.out.println("\tDEBUG: " + o.toString().replaceAll("\n", "\n\tDEBUG: "));
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement