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 nN = sc.nextInt();
        int nM = sc.nextInt();
        
        // 初期化
        boolean[] bSeat = new boolean[nN+1];    // 座席が埋まっているか?
        int nCustomer = 0;                      // 座っているお客の人数
        
        // 来店
        for (int i = 0; i < nM; i++) {
            int nA = sc.nextInt();   // 来店人数
            int nB = sc.nextInt();   // 座席の開始位置
           
            // 座席nB から nA人分の座席が空いているかを調べる
            boolean bSuccess = true;
            int nSeat = nB; 
            for (int j = 0; j < nA; j++) {
                if (bSeat[nSeat]) { // すでに座席が埋まっていた場合
                   bSuccess = false;
                   break;
                }
               
                // 次の座席番号にする
                nSeat++;
                if (nSeat > nN) { nSeat = 1; }
            }

            // 座ることに成功した場合
            if (bSuccess) {
                nCustomer += nA;     // 座れた人数を追加

                // 座席nB から nA人分座席を埋める
                nSeat = nB;
                for (int j = 0; j < nA; j++) {
                    bSeat[nSeat] = true;    // 座席を埋める
                    
                    // 次の座席番号にする
                    nSeat++;
                    if (nSeat > nN) { nSeat = 1; }
                }
            }
        }
        
        // 結果出力
        System.out.println(nCustomer);
    }
}

解説

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

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

初期化処理

  • 座席が埋まっているかを表す boolean 配列を作成
  • 座っている人の人数を0に設定

お客様の来店

標準入力から、来店人数 nA と、座席の最初の番号 nB を取得する。

座席が空いているか?

座席 nB から nA 人分の boolean 配列を調べ、全て false(空き)である場合、以下の処理を行う。

  • boolean 配列の調べた部分を true(着席済)に変える
  • 座っている人の人数を nA 人増やす

座席が1つでも埋まっていた場合

何もしません。(江戸っ子なので怒って帰りました(笑)。)

結果の出力

座っている人の人数を表示します。

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