티스토리 뷰

https://www.acmicpc.net/problem/11724

 

11724번: 연결 요소의 개수

첫째 줄에 정점의 개수 N과 간선의 개수 M이 주어진다. (1 ≤ N ≤ 1,000, 0 ≤ M ≤ N×(N-1)/2) 둘째 줄부터 M개의 줄에 간선의 양 끝점 u와 v가 주어진다. (1 ≤ u, v ≤ N, u ≠ v) 같은 간선은 한 번만 주

www.acmicpc.net

const fs = require('fs');
const input = fs.readFileSync("./dev/stdin").toString().trim().split("\n");


class Node {
  constructor(item) {
    this.item = item;
    this.next = null;
  }
}

class Queue {
  constructor() {
    this.head = null;
    this.tail = null;
    this.length = 0;
  }

  push(item) {
    const node = new Node(item)
    if (this.head === null) {
      this.head = node;
    } else {
      this.tail.next = node;
    }
    this.tail = node;
    this.length += 1;
  }

  pop() {
    const popItem = this.head.item;
    this.head = this.head.next;
    this.length -= 1;
    return popItem;
  }
}




const edge = input.map(v => v.split(' ').map(v => +v))
const [N, E] = edge.shift();
let adj = Array.from(Array(N + 1), () => []);
let isVisited = new Array(N + 1).fill(false)

edge.forEach(x => {
  const [u, v] = x;
  adj[v].push(u);
  adj[u].push(v);
})

let connect = 0;
let q = new Queue();
for (let i = 1; i <= N; i++) {
  if (!isVisited[i]) {
    isVisited[i] = true;
    connect++;
    q.push(i);
    while (q.length > 0) {
      let now = q.pop();
      adj[now].forEach(v => {
        if (!isVisited[v]) {
          q.push(v);
          isVisited[v] = true;
        }
      })
    }
  }
}

console.log(connect)
728x90
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/09   »
1 2 3 4 5 6 7
8 9 10 11 12 13 14
15 16 17 18 19 20 21
22 23 24 25 26 27 28
29 30
글 보관함