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?

More than 1 year has passed since last update.

paizaラーニング レベルアップ問題集 Aランクレベルアップメニュー JavaScript 重みあり有向グラフの隣接行列と隣接リスト

Last updated at Posted at 2022-11-07

重みあり有向グラフの隣接行列と隣接リスト (paizaランク B 相当)

解答例

隣接リストを作成する際、重みkを()の中に入れ、配列にします。

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);
//隣接行列g
let g = Array(N).fill(0).map(v => v = Array(N).fill(0));   
//隣接リストh
let h = Array(N).fill(0).map(v => v = []);

for (let i = 1; i <= M; i++) {
    //各辺の両端の頂点 a_i , b_i と、その辺の重み k_i 
    const [a, b, k] = lines[i].split(" ").map(Number);
    //隣接配列
    g[a - 1][b - 1] = k;
    //隣接リスト
    h[a - 1].push([b - 1, "(" + k + ")"]);
}

//隣接行列を出力
console.log(g.map(row => row.join("")).join("\n"));

//隣接リストの各行の頂点番号は昇順にソートして出力
console.log(
	h.map(row => row.sort((a, b) => a[0] - b[0])//頂点番号で昇順ソート
	                .map(elm => elm.join(""))//b-1とkをjoin
	                .join(""))//(b-1,k)と(b-1,k)を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

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?