※ 글쓴이는 취미로 코딩을 익혀보는 사람이라 정확하지 않은 내용을 담고 있을 수 있다 ※

 

이번에 볼 문제는 백준 24822번 문제인 Musical Trees이다.
문제는 아래 링크를 확인하자.

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

 

24822번: Musical Trees

The first line consists the number of people $n$ ($1\le n\le 100$) and the number of trees $m$ ($1 \le m \le 100$). The next line contains $n$ integers $p_1,p_2,\ldots,p_n$, the position of all the people when the music stops ($1 \le p_i \le 1\,000$). The

www.acmicpc.net

1에서 1000까지의 정수좌표에 사람들과 나무가 있을 때(단, 사람끼리와 나무끼리는 같은 좌표에 있지 않다) 각 사람들에게서 가장 가까운 나무가 무엇인지를 각각 조사한 뒤, 적어도 한 사람에게서 가장 가까운 나무의 개수를 출력하는 것으로 문제를 해결할 수 있다.

 

브루트포스로도 문제를 통과할 수 있지만, 사람들과 나무의 위치를 각각 정렬하여 sweeping을 이용하면 시간복잡도를 줄일 수도 있다.

 

아래는 제출한 소스코드이다.

#include <iostream>
#include <algorithm>
using namespace std;

int ppl[100];
int trees[102];
bool chk[101];

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

	int N, M; cin >> N >> M;
	for (int i = 0; i < N; i++) cin >> ppl[i];
	trees[0] = -1000000007;
	for (int i = 1; i <= M; i++) cin >> trees[i];
	trees[M + 1] = 1000000007;

	sort(ppl, ppl + N);
	sort(trees, trees + M + 2);

	int L = 0, R = 1;
	for (int i = 0; i < N; i++) {
		while (trees[R] < ppl[i]) L++, R++;
		if (ppl[i] - trees[L] > trees[R] - ppl[i]) chk[R] = 1;
		else chk[L] = 1;
	}

	for (int i = 1; i <= M; i++) {
		if (chk[i]) N--;
	}

	cout << N;
}
728x90

'BOJ' 카테고리의 다른 글

[BOJ 24819 // C++] Escape Wall Maria  (0) 2022.03.28
[BOJ 24818 // C++] Field Trip  (0) 2022.03.27
[BOJ 24820 // C++] Spelling Bee  (0) 2022.03.25
[BOJ 24751 // C++] Betting  (0) 2022.03.24
[BOJ 24745 // C++] Morse Code Palindromes  (0) 2022.03.23

+ Recent posts