0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

今回は paiza の「エスカレーター」の問題に挑戦!

問題概要

  • paizaビルのエスカレーターは
    • 長さ K メートル
    • 1秒で1メートル進む
  • 社員は N
  • 社員 i は 時刻 A_i に乗る

求めるもの

  • 各社員が 乗った直後の人数
  • 1人ごとに改行して出力



入力例:

4 3
1 3 4 6

出力例:

1
2
2
2






✅OK例:

const rl = require('readline').createInterface({ input: process.stdin });

const lines = [];
rl.on('line', line => lines.push(line));

rl.on('close', () => {
    const [N, K] = lines[0].split(' ').map(Number);
    const A = lines[1].split(' ').map(Number);

    const queue = [];      // エスカレーター(キュー)
    let idx = 0;           // 次に乗る社員のインデックス
    let current = 0;       // 現在エスカレーター上の人数

    const maxTime = A[N - 1];  // 最後に誰かが乗る時刻までシミュレート

    for (let t = 1; t <= maxTime; t++) {

        // K秒経過した人を降ろす
        if (queue.length === K) {
            const left = queue.shift();
            if (left === 1) {
                current--;   // 1なら社員が降りた
            }
        }

        // この時刻に社員が乗るか?
        if (idx < N && t === A[idx]) {
            queue.push(1);
            current++;
            console.log(current);
            idx++;
        } else {
            queue.push(0);
        }
    }
});

🔍コードの流れ

  1. 時刻 t を 1 から順に進める
  2. キューが K 個あれば先頭を削除(K秒経過)
  3. その値が 1 なら人数を減らす
  4. その時刻に社員が来たら
    • 1push
    • 人数を増やす
    • 出力
  5. 来なければ 0push






📝まとめ

エスカレーターに乗る人と降りる人を、キューの先入れ先出し(FIFO: First In, First Out)で表現。

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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?