Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
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 |
Tags
- 문자열
- 구현
- 그래프
- 투 포인터
- 브루트포스
- 유니티
- 백트래킹
- DFS
- 다익스트라
- 시뮬레이션
- 백준
- BFS
- 알고리즘
- Team Fortress 2
- 자료구조
- 수학
- 다이나믹 프로그래밍
- 우선순위 큐
- 재귀
- 스택
- 트리
- XR Interaction Toolkit
- 그리디 알고리즘
- 누적 합
- VR
- 유니온 파인드
- Unreal Engine 5
- ue5
- 정렬
- c++
Archives
- Today
- Total
1일1알
백준 18513번 샘터 C++ 본문
https://www.acmicpc.net/problem/18513
18513번: 샘터
첫째 줄에 자연수 N과 K가 공백을 기준으로 구분되어 주어진다. (1 ≤ N, K ≤ 100,000) 둘째 줄에 N개의 샘터의 위치가 공백을 기준으로 구분되어 정수 형태로 주어진다. (-100,000,000 ≤ 샘터의 위치 ≤
www.acmicpc.net
샘터 주변의 위치부터 탐색하면 된다.
샘터를 기준으로 -1, +1씩 검사하면서 지을 수 있으면 짓고 큐에 그 위치를 넣고 하면서 k개의 집을 지었을 때 불행도를 합치면 된다.
#include <iostream>
#include <string>
#include <vector>
#include <math.h>
#include <algorithm>
#include <utility>
#include <stack>
#include <queue>
#include <math.h>
#include <set>
#include <map>
#include <list>
#include <unordered_map>
#include <unordered_set>
#include <iomanip>
#include <limits.h>
using namespace std;
using int64 = long long;
int n, k;
int64 ans = 0;
unordered_set<int> us;
int main() {
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
cin >> n >> k;
queue<pair<int,int>> q;
for (int i = 0; i < n; i++) {
int loc;
cin >> loc;
q.push({loc,0});
us.insert(loc);
}
int cnt = 0;
while (!q.empty()) {
auto curr = q.front();
q.pop();
int back = curr.first - 1;
auto it = us.find(back);
if (it == us.end()) {
ans += abs(curr.second - 1);
cnt++;
if (cnt == k) break;
q.push({ back,curr.second - 1 });
us.insert(back);
}
int front = curr.first + 1;
it = us.find(front);
if (it == us.end()) {
ans += abs(curr.second + 1);
cnt++;
if (cnt == k) break;
q.push({ front,curr.second + 1 });
us.insert(front);
}
}
cout << ans;
}
'알고리즘' 카테고리의 다른 글
백준 14713번 앵무새 C++ (0) | 2023.02.27 |
---|---|
백준 1972번 놀라운 문자열 C++ (0) | 2023.02.25 |
백준18429번 근손실 C++ (0) | 2023.02.23 |
백준 11265번 끝나지 않는 파티 C++ (0) | 2023.02.22 |
백준 10166번 관중석 C++ (0) | 2023.02.21 |