ABC047 B - Snuke's Coloring 2 (ABC Edit)

備忘録

問題

atcoder.jp

回答

"use strict"
function Main(input) {
  input = input.trim().split('\n');
  let WHN = input[0].split(' ').map(Number);
  let minX = 0;
  let minY = 0;
  let maxX = WHN[0];
  let maxY = WHN[1];
  const N = WHN[2];

  for(let i=1; i<=N; i++){
    let tmp = input[i].trim().split(' ').map(Number)
    let A = tmp[2];
    if(A === 1){
      if(tmp[0] > minX){
        minX = tmp[0];
      }
    } else if (A === 2) {
      if(tmp[0] < maxX){
        maxX = tmp[0];
      }
    } else if (A === 3) {
      if(tmp[1] > minY) {
        minY = tmp[1];
      }
    } else if (A === 4) {
      if(tmp[1] < maxY) {
        maxY = tmp[1];
      }
    }
  }

  const X = maxX - minX;
  const Y = maxY - minY;
  if(X <= 0 || Y <= 0){
    console.log(0);
  } else {
    console.log(X*Y);
  }
}
Main(require("fs").readFileSync("/dev/stdin", "utf8"));

考え方

まず、最小のx0、最大をW、最小のy0、最大をHとする。

aの各パターン時にxyの位置が更新される。

  • a = 1
    xixの最小値を上回る場合、xの最小値をxiに更新する。

  • a = 2
    xixの最大値を下回る場合、xの最大値をxiに更新する。

  • a = 3
    yiyの最小値を上回る場合、yの最小値をyiに更新する。

  • a = 4
    yiyの最大値を下回る場合、yの最大値をyiに更新する。

全ての座標でxyの最大値と最小値を更新したあと、残った座標から面積を算出するだけ。

注意しなければならないのは、面積を算出するとき、最大値と最小値の差分で負の数が発生する場合があるので、差の結果が負の場合は0を出力すること。