0
0

解いてみた。「Bランク:神経衰弱」

Posted at

問題

「Bランク:神経衰弱」

コード

Javaで解いてみました。

import java.util.*;

public class Main {
    public static void main(String[] args) {
        
        Scanner sc = new Scanner(System.in);
        int nH = sc.nextInt();  // カード枚数(垂直方向)
        int nW = sc.nextInt();  // カード枚数(水平方向)
        int nN = sc.nextInt();  // プレイヤー人数

        int[][] anT = new int[nH+1][nW+1];
        
        // カード読み込み
        for (int h = 1; h <= nH; h++) {
            for (int w = 1; w <= nW; w++) {
                anT[h][w] = sc.nextInt();
            }
        }

        int nL = sc.nextInt();  // 記録の個数
        
        int[] anScore = new int[nN+1];  // n番目のプレイヤーの取得枚数
        int nTurn = 1;                  // 手番のプレイヤー番号
        int nRest = nW * nH;            // 場に残っている枚数

        // ゲームプレイ
        while (nRest > 0) {
            int na = sc.nextInt();
            int nb = sc.nextInt();
            int nA = sc.nextInt();
            int nB = sc.nextInt();
            
            if (anT[na][nb] == anT[nA][nB]) {   // カードの数が一致した。
                anScore[nTurn] += 2;
                nRest -= 2;
                // 同じ手番の人がプレイ
            } else {
                // 次の手番
                nTurn++;
                if (nTurn > nN) { nTurn = 1; }
            }
        }
        
        // 結果出力
        for (int n = 1; n <= nN; n++) {
            System.out.println(anScore[n]);
        }
    }
}

解説

標準入力からの数値の読み取り

数値(場のカード枚数(縦、横)、プレイ人数)の取得

Scanner インスタンスを作り、nextInt()メソッドで各数値を取得しています。

カードの配置の取得

配列 anT[][] に格納していきますが、後々位置が、行(1〜H)、列(1〜W)で指定されることを考慮して、配列のサイズを anT[nH+1][nW+1] としています。

記録の数の取得

Scanner インスタンスを作り、nextInt()メソッドで数値を取得しています。

実行前の初期処理

  • 各プレイヤーの取得した枚数を配列で用意
  • 手番(1〜N)を1に設定
  • 残り枚数を nW $\times$ nH に設定します。
    ## ゲームの実行ループ
    残り枚数が0より大きい間、while ループを回します

記録の取得

1枚目の行na、列nbと2枚目の行nA、列nBを、標準入力から取得します。

カードの比較

anT[na][nb] と anT[nA][nB]を比較します。

数字が一致した場合

  • プレイヤーの取得した枚数を +2 します。
  • 残り枚数を -2 します。
  • 手番はそのままです。

数字が一致しなかった場合

  • 次のプレイヤーに手番を移動します。

結果の出力

プレイヤーの取得した枚数を表示します。

その他

問題の性質上、カードを取り除く処理や、取り除かれたカードが選択されることは考えていません。

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0