작성일 :

문제 링크

2166번 - 다각형의 면적

설명

꼭짓점 좌표가 순서대로 주어진 단순 다각형의 면적을 구하는 문제입니다.

신발끈 공식을 사용하면 한 번의 순회로 면적을 계산할 수 있습니다. 결과는 소수점 첫째 자리까지 반올림하여 출력합니다.


접근법

먼저, 좌표를 배열에 담고 순회하면서 각 꼭짓점과 다음 꼭짓점의 외적을 누적합니다. 마지막 점의 다음은 첫 점과 연결합니다.

다음으로, 누적된 값의 절댓값을 2로 나누면 최종 면적이 됩니다.



Code

C#

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
using System;

namespace Solution {
  class Program {
    static void Main(string[] args) {
      var n = int.Parse(Console.ReadLine()!);
      var x = new double[n];
      var y = new double[n];
      for (var i = 0; i < n; i++) {
        var p = Console.ReadLine()!.Split();
        x[i] = double.Parse(p[0]);
        y[i] = double.Parse(p[1]);
      }

      var cross = 0.0;
      for (var i = 0; i < n; i++) {
        var j = (i + 1) % n;
        cross += x[i] * y[j] - x[j] * y[i];
      }

      var area = Math.Abs(cross) / 2.0;
      Console.WriteLine(area.ToString("0.0"));
    }
  }
}

C++

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
#include <bits/stdc++.h>
using namespace std;
typedef vector<double> vd;

int main() {
  ios::sync_with_stdio(false);
  cin.tie(nullptr);

  int n; cin >> n;
  vd x(n), y(n);
  for (int i = 0; i < n; i++)
    cin >> x[i] >> y[i];

  double cross = 0;
  for (int i = 0; i < n; i++) {
    int j = (i + 1) % n;
    cross += x[i] * y[j] - x[j] * y[i];
  }

  double area = fabs(cross) / 2.0;
  cout << fixed << setprecision(1) << area << "\n";

  return 0;
}