1
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の「歴史を作る時間」の問題に挑戦!

クエリメニューの範囲だけど、クエリじゃなかった!?


問題概要

  • グループの人数 N とメンバー名リスト
  • 出来事の数 K と、それぞれの起きた年 Y_i と担当者名 C_i
  • 出来事を年の古い順に並べ、担当者を順番に出力



入力例:

3 5
nao
hiro
yuki
645 nao
593 hiro
2058 yuki
29484 nao
374759 nao

出力例:

hiro
nao
yuki
nao
nao






❌ NG例:キーの重複

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

rl.on('line', (input) => lines.push(input));


rl.on('close', () => {
    const [N, K] = lines[0].split(' ').map(Number);
    const students = lines.slice(1, N+1);
    
    
    const timeLine = new Map(lines
      .slice(N+1)
      .map(line => {
          const [year, name] = line.split(' ');
          return [year, name];
      }));
      
      
    Array.from(timeLine.keys())
      .sort((a,b) => a-b)
      .forEach(t => {
          console.log(timeLine.get(t))
      });
});

同じ年に複数の出来事があった場合、キーが重複してまい、片方しか残らないからNG!




✅ OK例:オブジェクト

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

rl.on('line', input => lines.push(input));

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

  const timeLine = lines.slice(N+1).map(line => {
      const [year, name] = line.split(' ');
      return {year : Number(year), name};
      });

    // 年代順にソート
  timeLine.sort((a,b) => a.year - b.year);

    // 担当者を順番に出力
  timeLine.forEach(t => console.log(t.name));
});




✨超シンプル例:配列

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

rl.on('line', input => lines.push(input));

rl.on('close', () => {
  const [N, K] = lines[0].split(' ').map(Number);
  const names = lines.slice(1, N + 1); // 使わないけど読み込み

  // 歴史の出来事([year, name]の配列)を作成
  const histories = lines.slice(N + 1, N + 1 + K).map(line => {
    const [year, name] = line.split(' ');
    return [Number(year), name];
  });

  // 年でソート。Numberなので数値比較
  histories.sort((a, b) => a[0] - b[0]);

  // 担当者名だけ出力
  histories.forEach(([year, name]) => console.log(name));
});






🗒️ メモ・まとめ

  • Map はキーの重複を許さない

  • 名前も年も複数回出現する可能性があるので、同じキーで上書きされてしまい正しく管理できない



ちなみに、クエリの問題ではなかったそうです😡

入力が複数個与えられているのでこの問題も入力ごとに処理をおこなうクエリの問題に見えますが、結論から言うとこの問題はクエリの問題ではありません(ひっかけです、すみません)
https://paiza.jp/works/mondai/reviews/show/a416d297de859c03a83e8ae5000c0bd2




僕の失敗談(´;ω;`)と解決法🐈

1
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
1
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?