結果

問題 No.643 Two Operations No.2
ユーザー GrenacheGrenache
提出日時 2018-02-02 22:04:51
言語 Java
(openjdk 23)
結果
AC  
実行時間 164 ms / 2,000 ms
コード長 1,895 bytes
コンパイル時間 4,329 ms
コンパイル使用メモリ 80,144 KB
実行使用メモリ 54,388 KB
最終ジャッジ日時 2024-12-31 07:35:20
合計ジャッジ時間 6,557 ms
ジャッジサーバーID
(参考情報)
judge5 / judge2
このコードへのチャレンジ
(要ログイン)
ファイルパターン 結果
other AC * 13
権限があれば一括ダウンロードができます

ソースコード

diff #

import java.io.*;
import java.util.*;


public class Main_yukicoder643 {

	private static Scanner sc;
	private static Printer pr;

	private static void solve() {
		int x = sc.nextInt();
		int y = sc.nextInt();

		Map<Pair, Integer> dp = new HashMap<>();
		dp.put(new Pair(x, y), 0);
		Queue<Pair> q = new ArrayDeque<>();
		q.add(new Pair(x, y));
		while (!q.isEmpty()) {
			Pair e = q.remove();
//			pr.println(e);

			if (e.a == e.b) {
				int ans = dp.get(e);
				if (ans > 100) {
					pr.println(-1);
				} else {
					pr.println(ans);
				}
//				pr.println(dp.get(e));
//				pr.println(e);
				return;
			}

			Pair tmp = new Pair(e.b, e.a);
			if (!dp.containsKey(tmp)) {
				q.add(tmp);
				dp.put(tmp, dp.get(e) + 1);
			}
			tmp = new Pair(e.a + e.b, e.a - e.b);
			if (!dp.containsKey(tmp)) {
				q.add(tmp);
				dp.put(tmp, dp.get(e) + 1);
			}
		}
	}

	private static class Pair implements Comparable<Pair> {
		long a;
		long b;

		Pair(long a, long b) {
			this.a = a;
			this.b = b;
		}

		@Override
		public int compareTo(Pair o) {
			if (a == o.a) {
				return Long.compare(b, o.b);
			}

			return Long.compare(a, o.a);
		}

		@Override
		public int hashCode() {
			return Long.hashCode(a);
		}

		@Override
		public boolean equals(Object obj) {
			return a == ((Pair)obj).a && b == ((Pair)obj).b;
		}

		@Override
		public String toString() {
			// [xxx, xxxx]
			StringBuilder stmp = new StringBuilder(32);
			stmp.append('[');
			stmp.append(a);
			stmp.append(',');
			stmp.append(' ');
			stmp.append(b);
			stmp.append(']');

			return stmp.toString();
		}
	}

	// ---------------------------------------------------
	public static void main(String[] args) {
		sc = new Scanner(System.in);
		pr = new Printer(System.out);

		solve();

		pr.close();
		sc.close();
	}

	private static class Printer extends PrintWriter {
		Printer(PrintStream out) {
			super(out);
		}
	}
}
0