0
0

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 Aランクレベルアップメニュー JavaScript 隣接リスト

Posted at

隣接リスト (paizaランク B 相当)

解答例

問題文に沿って実装します。ソートをすることを覚えておいてください。

const fs = require("fs");
const input = fs.readFileSync("/dev/stdin", "utf-8").trim();
const lines = input.split("\n");

//頂点の数 N と、辺の数 M 
const [N, M] = lines[0].split(" ").map(Number);

//隣接リストh
//準備
let h  = [];
for (let i = 1; i <= N; i++) {
    h.push([]);
}

for (let i = 1; i <= M; i++) {
    const [a, b] = lines[i].split(" ").map(Number);
    //隣接リスト作成
    h[a - 1].push(b - 1);
    h[b - 1].push(a - 1);
}

//隣接リストの各行の頂点番号は昇順にソート
h.map(row =>row.sort((a, b) => a - b));

//隣接リスト出力
console.log(h.map(row => row.join("")).join("\n"));

準備のところは1行でも書けます。

//準備
let h  = Array(N).fill(0).map(v => v = []);

ソートと出力の部分は、まとめられます。

//隣接リストの各行の頂点番号は昇順にソート
//隣接リスト出力
console.log(h.map(row => row.sort((a, b) => a - b).join("")).join("\n"));
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