본문 바로가기
백준 알고리즘/백준 CLASS 5

[백준 C++] 2166번: 다각형의 면적

by code_killer 2023. 6. 9.
728x90
반응형

1. 문제

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

 

2166번: 다각형의 면적

첫째 줄에 N이 주어진다. 다음 N개의 줄에는 다각형을 이루는 순서대로 N개의 점의 x, y좌표가 주어진다. 좌표값은 절댓값이 100,000을 넘지 않는 정수이다.

www.acmicpc.net

 

2. 알고리즘 분류

  • 기하학
  • 다각형의 넓이

 

3. 소스 코드

#include <iostream>
#include <vector>
#include <cmath>

using namespace std;

vector<pair<double, double>> polygon_coord; // 다각형 좌표 데이터

int main()
{
	// N 값 입력
	int N;
	scanf("%d", &N);

	// 다각형의 좌표 입력
	for (int i = 0; i < N; i++)
	{
		double x, y;
		scanf("%lf %lf", &x, &y);

		polygon_coord.push_back({ x, y });
	}

	double res = 0;

	// 다각형의 넓이를 구하는 공식 대입
	for (int i = 1; i < N - 1; i++)
	{
		double x1 = polygon_coord[0].first;
		double x2 = polygon_coord[i].first;
		double x3 = polygon_coord[i + 1].first;
		double y1 = polygon_coord[0].second;
		double y2 = polygon_coord[i].second;
		double y3 = polygon_coord[i + 1].second;

		double tmp = (x1 * y2 + x2 * y3 + x3 * y1) - (y1 * x2 + y2 * x3 + y3 * x1);
		tmp /= 2;

		res += tmp;
	}

	// 소수점 첫째자리까지 출력
	printf("%.1lf", abs(res));

	return 0;
}
728x90