알고리즘/BOJ

백준 15970번 화살표 그리기

꾸준함. 2020. 2. 14. 00:14

문제 링크입니다: https://www.acmicpc.net/problem/15970

 

15970번: 화살표 그리기

직선 위에 위치를 나타내는 0, 1, 2, ...와 같은 음수가 아닌 정수들이 일정한 간격으로 오른쪽 방향으로 놓여 있다. 이러한 위치들 중 N개의 위치에 하나씩 점들이 주어진다(<그림 1>). 주어진 점들의 위치는 모두 다르다. 두 점 사이의 거리는 두 점의 위치를 나타내는 수들의 차이이다. <그림 1>에서는 4개의 점이 주어지고 점 a와 b의 거리는 3이다. <그림 1> 각 점은 N개의 색깔 중 하나를 가진다. 편의상, 색깔은 1부터 N까지의 수로 표

www.acmicpc.net

각 색깔마다 좌표들을 저장하고 오름차순 정렬을 한 뒤 가장 가까운 점끼리 직선을 이은 거리들의 합을 구하면 되는 문제였습니다.

자세한 내용은 코드 주석을 참고해주세요.

 

#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
const int MAX = 5000 + 1;
vector<int> coords[MAX];
int main(void)
{
ios_base::sync_with_stdio(0);
cin.tie(0);
int N;
cin >> N;
for (int i = 0; i < N; i++)
{
int coord, color;
cin >> coord >> color;
coords[color].push_back(coord);
}
long long result = 0;
for (int color = 1; color < MAX; color++)
{
// 해당 색깔이 없다면 pass
if (coords[color].empty())
{
continue;
}
sort(coords[color].begin(), coords[color].end());
// 최좌측 점은 바로 오른쪽에 있는 점과 이어지고
result += coords[color][1] - coords[color][0];
for (int j = 1; j < coords[color].size() - 1; j++)
{
int x = coords[color][j];
// 양 옆 점 중 최소 거리를 결과에 더한다
result += min(x - coords[color][j - 1], coords[color][j + 1] - x);
}
int lastIdx = coords[color].size() - 1;
// 최우측 점은 바로 좌측에 있는 점과 이어집니다.
result += coords[color][lastIdx] - coords[color][lastIdx - 1];
}
cout << result << "\n";
return 0;
}
view raw .cpp hosted with ❤ by GitHub

개발환경:Visual Studio 2017

 

지적, 조언, 질문 환영입니다! 댓글 남겨주세요~

반응형

'알고리즘 > BOJ' 카테고리의 다른 글

백준 14395번 4연산  (0) 2020.02.17
백준 2941번 크로아티아 알파벳  (0) 2020.02.16
백준 5639번 이진 검색 트리  (2) 2020.02.07
백준 1244번 스위치 켜고 끄기  (4) 2020.02.05
백준 13459번 구슬 탈출  (0) 2020.02.05