はじめに
自分用の備忘録。
目次
問題
問題のポイント
- 連想配列を使うこと
- 入力値には2つのタイプがあるので、それを処理する。例えば 今回の場合は、1と2の場合がある。1.
1 tanaka 49
2.2 tanaka
連想配列を試すのにいい教材だなって思いました。基礎が固まった気がします。
今回の問題のイメージ。インプットを配列に格納するときのイメージ。
自分がミスしたところ 2024年4月9日
今回は、配列に格納せずにそのままプログラムを書いた。(解答例その2を参照)。一回、if
分の前でしっかりと受け止めてやらないといけない。愛で包み込む。
文法的な話をします。1つ目のif
の後に2つ目のif
に行くわけですが、まあ、そうすると入力値受けすぎ、あれ、おれ、こいつと型合わないんですけど、みたいな事態が起こる。下記に誤った例を書いておきます。
誤った例
if (sc.nextInt() == 1) { map.put(sc.next(), sc.nextInt()); } if (sc.nextInt() == 2) { int temp = map.get(sc.next()); System.out.println(temp); } }
正しい方
// ここで入力値を受け取っちゃいます int intTemp = sc.nextInt(); // 受け取った値をもとに判別します! if (intTemp == 1) { map.put(sc.next(), sc.nextInt()); } if (intTemp == 2) { int temp = map.get(sc.next()); System.out.println(temp); }
Query Type : 1, 1, 2 Query x : tanaka, suzuki, tanaka Query y : 49, 50, (Query Typeが2だから何もないよ。出力せよ)
問題の解答例
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); // インプットを処理します。 int Q = sc.nextInt(); // 入力を入れる配列を用意!今回はだいたいQくらいの箱を用意してあげるとよき int[] queryType = new int[Q + 1]; String[] x = new String[Q + 1]; int[] y = new int[Q + 1]; // じゃあ、今からインプットされた情報を配列に入れていくよー for (int i = 1; i <= Q; i++) { // 今回クエリのタイプが2つあったよね。それを識別するのに大切 queryType[i] = sc.nextInt(); // じゃあ、クエリのタイプが1の場合は、xとyに入れよ! if (queryType[i] == 1) { x[i] = sc.next(); y[i] = sc.nextInt(); } // じゃあ、クエリのタイプが2の場合は、こう入れよ! if (queryType[i] == 2) { x[i] = sc.next(); } } // ここで連想配列を用意 Map<String, Integer> scoreMap = new HashMap<String, Integer>(); // 処理を進めていくよ for (int i = 1; i <= Q; i++) { // もしクエリのタイプが1の場合は、値を格納せよ。putだ! if (queryType[i] == 1) { // KeyとValueで指定してあげるよ。田中君の点数は100点満点、的なイメージ。 scoreMap.put(x[i], y[i]); } // もし、タイプが2なら出力せよ! if (queryType[i] == 2) { System.out.println(scoreMap.get(x[i])); } } sc.close(); } }
解答例その2
import java.util.*; public class Main { public static void main(String[] args) { Scanner sc = new Scanner(System.in); Map<String, Integer> map = new HashMap<String, Integer>(); int q = sc.nextInt(); for (int i = 0; i < q; i++) { int intTemp = sc.nextInt(); if (intTemp == 1) { map.put(sc.next(), sc.nextInt()); } if (intTemp == 2) { int temp = map.get(sc.next()); System.out.println(temp); } } sc.close(); } }
参考文献
https://atcoder.jp/contests/tessoku-book/tasks/tessoku_book_bb