問題
コード
Javaで解いてみました。
import java.util.*;
// 文字列とその値段を保持するクラス
class StrPrice {
public String str = "";
public int price = 0;
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int nN = sc.nextInt();
int nM = sc.nextInt();
// 文字列とその値段の読み込み
StrPrice[] asp = new StrPrice[nN];
for (int i = 0; i < nN; i++) {
StrPrice tmp = new StrPrice();
tmp.str = sc.next();
tmp.price = sc.nextInt();
asp[i] = tmp;
}
// 購入する
for (int i = 0; i < nM; i++) {
String sQ = sc.next();
int nPrice = 0;
for (int j = 0; j < nN; j++) {
if (asp[j].str.startsWith(sQ)) {
nPrice += asp[j].price;
}
}
// 結果出力
System.out.println(nPrice);
}
}
}
解説
標準入力からの数値の読み取り
Scanner インスタンスを作り、nextInt()メソッドで数値を取得しています。
文字列とその値段の読み込み
next()メソッドとnextInt()メソッドによる読み取りを行い、クラスStrPrice に格納し、配列に保存します。
集める文字列の検索と値段の合計
String クラスの startsWith() メソッドを用いて、文字列が前方一致するか調べます。一致した場合、買い(値段を足し)ます。