백준 (16234) 인구이동 (JS)

Sming·2021년 9월 25일
0

문제

N×N크기의 땅이 있고, 땅은 1×1개의 칸으로 나누어져 있다. 각각의 땅에는 나라가 하나씩 존재하며, r행 c열에 있는 나라에는 A[r][c]명이 살고 있다. 인접한 나라 사이에는 국경선이 존재한다. 모든 나라는 1×1 크기이기 때문에, 모든 국경선은 정사각형 형태이다.

오늘부터 인구 이동이 시작되는 날이다.

인구 이동은 하루 동안 다음과 같이 진행되고, 더 이상 아래 방법에 의해 인구 이동이 없을 때까지 지속된다.

국경선을 공유하는 두 나라의 인구 차이가 L명 이상, R명 이하라면, 두 나라가 공유하는 국경선을 오늘 하루 동안 연다.
위의 조건에 의해 열어야하는 국경선이 모두 열렸다면, 인구 이동을 시작한다.
국경선이 열려있어 인접한 칸만을 이용해 이동할 수 있으면, 그 나라를 오늘 하루 동안은 연합이라고 한다.
연합을 이루고 있는 각 칸의 인구수는 (연합의 인구수) / (연합을 이루고 있는 칸의 개수)가 된다. 편의상 소수점은 버린다.
연합을 해체하고, 모든 국경선을 닫는다.
각 나라의 인구수가 주어졌을 때, 인구 이동이 며칠 동안 발생하는지 구하는 프로그램을 작성하시오.

입력

첫째 줄에 N, L, R이 주어진다. (1 ≤ N ≤ 50, 1 ≤ L ≤ R ≤ 100)

둘째 줄부터 N개의 줄에 각 나라의 인구수가 주어진다. r행 c열에 주어지는 정수는 A[r][c]의 값이다. (0 ≤ A[r][c] ≤ 100)

인구 이동이 발생하는 일수가 2,000번 보다 작거나 같은 입력만 주어진다.

코드

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

const mapInfo = input[0].split(" ");
const n = parseInt(mapInfo[0]);
const L = parseInt(mapInfo[1]);
const R = parseInt(mapInfo[2]);
const Map = input
  .slice(1, input.length)
  .map((e) => e.split(" ").map((d) => parseInt(d)));
const dx = [0, 0, 1, -1];
const dy = [1, -1, 0, 0];
const ans = {};
let flag = true;
class Queue {
  constructor() {
    this.q = {};
    this.front = 0;
    this.rear = 0;
    this.size = 0;
  }
  get getQueueSize() {
    return this.size;
  }
  init() {
    this.q = {};
    this.size = 0;
    this.front = 0;
    this.rear = 0;
  }

  push(data) {
    this.q[++this.rear] = data;
    this.size++;
  }

  pop() {
    this.size--;
    return this.q[++this.front];
  }

  isEmpty() {
    return this.front === this.rear;
  }
}

const queue = new Queue();

const bfs = (x, y, value, check) => {
  queue.push([x, y]);
  check[x][y] = value;
  let sum = Map[x][y];
  let num = 1;
  while (queue.getQueueSize) {
    const Point = queue.pop();
    const x = Point[0];
    const y = Point[1];
    for (let i = 0; i < 4; i++) {
      const nx = x + dx[i];
      const ny = y + dy[i];
      if (nx < 0 || ny < 0 || nx >= n || ny >= n || check[nx][ny] > 0) {
        continue;
      }
      const target = Math.abs(Map[x][y] - Map[nx][ny]);
      if (target >= L && target <= R) {
        queue.push([nx, ny]);
        check[nx][ny] = value;
        sum += Map[nx][ny];
        num += 1;
        flag = true;
      }
    }
  }
  return { sum, num };
};

const reSettingMap = (check) => {
  for (let i = 0; i < n; i++) {
    for (let j = 0; j < n; j++) {
      Map[i][j] = ans[check[i][j]];
    }
  }
};

const solution = () => {
  let realAnswer = 0;
  let cnt = 1;
  while (true) {
    flag = false;
    const check = Array.from(Array(n), () => new Array(n).fill(0));
    Map.forEach((mapElement, i) => {
      mapElement.forEach((e, j) => {
        if (check[i][j] === 0) {
          const { sum, num } = bfs(i, j, cnt, check);
          const avg = Math.floor(sum / num);
          ans[cnt] = avg;
          cnt++;
        }
      });
    });
    if (!flag) {
      return realAnswer;
    }
    reSettingMap(check);
    realAnswer += 1;
  }
};

console.log(solution());

먼저 bfs를 돌며 그 인구의 연합들을 묶어준다.sum과 num을 더해주면서 진행을 하며 ans객체에 평균값을 넣어주며 reSettingMap을 이용하여 연합별로 바뀐 value를 모두 바꿔준뒤 시간을 1늘린후 bfs를 반복해준다.

profile
딩구르르

0개의 댓글

Powered by GraphCDN, the GraphQL CDN