はじめに
競技プログラミングの鉄則を読み進めているので、自分で解いた記録を残します。今回解いた問題はこちら。「A28 - Blackboard 」。それでは楽しんでいってください!
今回の問題のポイント
整数の性質がポイントでしたね。
足し算、引き算、掛け算では好きなタイミングで余りをとっても答え(余り)は変わらないっていうこと。これの競技プログラミングの鉄則、ぜひ買って読んでみてほしい。解説が分かりやすかったです。著者の米田さん。ありがとうございます。
自分がミスったポイント
- 正しくコピペできていなかった。
1000
を10000
だと思ってずっと苦戦していた。 Java
なので、String
の値を比較するときはString.equals()
にしないとですね。- 普通に一文字だけの時は
charactor
使おう。そっちの方がめんどくさくなさそう。いや、Stringのメソッドたちも捨てにくい。 - 無駄に長いコード。同じ意味のコードばかり繰り返している。だからまとめたよ!
目次
問題と公式の解説
問題
公式の解説
改良版 解答例
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] t = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { t[i] = sc.next(); a[i] = sc.nextInt(); } int ans = 0; for (int i = 0; i < n; i++) { ans = Divisor(t[i], a[i], ans); System.out.println(ans); } } private static int Divisor(String x, int y, int answer) { int value = 10000; if (x.equals("+")) { answer += y; } if (x.equals("-")) { answer -= y; } if (x.equals("*")) { answer *= y; } if (answer < 0) { answer += value; } answer %= value; return answer; } }
解答例
もう少し短くできますね。重複は削除しないとですよね^^.
import java.util.Scanner; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); int n = sc.nextInt(); String[] t = new String[n]; int[] a = new int[n]; for (int i = 0; i < n; i++) { t[i] = sc.next(); a[i] = sc.nextInt(); } int ans = 0; for (int i = 0; i < n; i++) { // System.out.println(t[i]); // System.out.println(a[i]); // System.err.println(ans); ans = Divisor(t[i], a[i], ans); System.out.println(ans); } } private static int Divisor(String x, int y, int answer) { // 改良ポイント。tempに代入しようがしまいが、正味変わらない。上記の例(改良版 解答例)を参考にしてね。 String tempX = x; int tempY = y; int tempAns = answer; int value = 10000; if (tempX.equals("+")) { tempAns += tempY; } if (tempX.equals("-")) { tempAns -= tempY; } if (tempX.equals("*")) { tempAns *= tempY; } if (tempAns < 0) { tempAns += value; } tempAns %= value; return tempAns; } }