일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
- 조합론
- 회고록
- BFS
- 미래는_현재와_과거로
- 알고리즘
- 백트래킹
- lazy propagation
- 세그먼트 트리
- pytorch
- dfs
- 다익스트라
- tensorflow
- object detection
- 2023
- c++
- 분할 정복
- 자바스크립트
- DP
- 크루스칼
- back propagation
- 문자열
- 플로이드 와샬
- 너비 우선 탐색
- 가끔은 말로
- 우선 순위 큐
- dropout
- Overfitting
- NEXT
- 이분 탐색
- 가끔은_말로
- Today
- Total
Doby's Lab
백준 6194번: Buliding the Moat (C++) 본문
https://www.acmicpc.net/problem/6194
6194번: Building the Moat
To repel the invading thirsty aardvarks, Farmer John wants to build a moat around his farm. He owns N (8 <= N <= 5,000) watering holes, and will be digging the moat in a straight line between pairs of them. His moat should protect (i.e., surround) all
www.acmicpc.net
Solved By: Convex Hull
Graham Scan 기법을 이용한 Convex Hull을 활용하여 모든 watering holes를 보호해야 합니다.
구한 점들을 가지고서 점들 사이의 거리를 구하면 됩니다.
이때 저번에 어디선가 본 테크닉을 이용하였습니다.
j가 끝점이 되는데 끝점에서 시작점까지의 거리를 복잡하게 구현하지 않고 나머지 연산을 이용하여 다음과 같이 편하게 구할 수 있습니다.
for(int i = 0; i < s.size(); i++){
int j = (1 + i) % s.size();
result += dist(p[s[i]], p[s[j]]);
}
그리고, 이번에 이 테크닉이 사용 가능했던 이유는 점들의 데이터를 담은 data structure가 stack이 아닌 vector로 풀어보았기 때문입니다.
+ 이번에는 typedef을 사용하지 않고, [struct 타입명]의 방식으로 struct를 선언하였습니다. typedef가 옛 방식이라는 것을 보고, 다른 방법으로 시도해보았습니다.
결론적으로 이번 문제의 핵심은 풀었던 방식입니다.
- stack 대신 vector 사용
- 끝점과 시작점 사이의 거리 간단하게 구현하기
#include <iostream>
#include <algorithm>
#include <vector>
#include <cmath>
#define ll long long
#define ld long double
#define pu push_back
#define po pop_back
using namespace std;
struct Point{
ll x, y;
};
int n;
vector<Point> p;
ll ccw(Point a, Point b, Point c){
return (b.x - a.x) * (c.y - a.y) - (c.x - a.x) * (b.y - a.y);
}
ld dist(Point a, Point b){
return (ld)sqrtl(powl(a.x - b.x, 2) + powl(a.y - b.y, 2));
}
bool cmp(Point a, Point b){
if(a.y != b.y) return a.y < b.y;
return a.x < b.x;
}
bool cmp2(Point a, Point b){
ll ccwv = ccw(p[0], a, b);
if(ccwv == 0) return dist(p[0], a) < dist(p[0], b);
return ccwv > 0;
}
ld convexHull(){
vector<int> s;
s.pu(0); s.pu(1);
int next = 2;
while(next < n){
while(s.size() >= 2){
int first, second;
second = s[s.size() - 1]; s.po();
first = s[s.size() - 1];
if(ccw(p[first], p[second], p[next]) > 0){
s.pu(second); break;
}
}
s.pu(next++);
}
ld result = 0;
for(int i = 0; i < s.size(); i++){
int j = (1 + i) % s.size();
result += dist(p[s[i]], p[s[j]]);
}
return result;
}
int main(){
cin >> n;
for(int i = 0; i < n; i++){
ll a, b; cin >> a >> b;
p.pu({a, b});
}
sort(p.begin(), p.end(), cmp);
sort(p.begin() + 1, p.end(), cmp2);
cout << fixed;
cout.precision(2);
cout << convexHull();
return 0;
}
'PS > BOJ' 카테고리의 다른 글
백준 17403번: 가장 높고 넓은 성 (C++) (0) | 2022.04.21 |
---|---|
백준 13232번: Domain clusters (C++) (0) | 2022.04.19 |
백준 6850번: Cows (C++) (0) | 2022.04.17 |
백준 10903번: Wall construction (C++) (0) | 2022.04.16 |
백준 2992번: 크면서 작은 수 (C++) (0) | 2022.04.13 |