Skip to content

9-Kaifeel - #39

Open
Kaifeel wants to merge 1 commit into
mainfrom
9-Kaifeel
Open

9-Kaifeel#39
Kaifeel wants to merge 1 commit into
mainfrom
9-Kaifeel

Conversation

@Kaifeel

@Kaifeel Kaifeel commented Aug 16, 2026

Copy link
Copy Markdown
Collaborator

문제 링크

Cookies and Greedy Takahashi

소요 시간

30분

접근 과정

0번째 자리에서 가까운 자리로 이동하는데, 좌표가 가장 작은 것부터 이동하는 조건이 있어서 정렬을 하고 상황에 맞게 포인터를 이동하면 되겠다고 생각했습니다!

풀이 설명

마이너스 좌표가 담긴 벡터의 경우 정렬하면 절댓값이 큰 숫자가 앞으로 가서 역으로 정렬을 해줍니다.
플러스 좌표인 경우는 정렬하면 오름차순으로 됩니다 두 벡터에 대해서 포인터를 두고 움직입니다.

마이너스에서 플러스로 가는 경우와 그 반대 경우는 거리 값이 크기 때문에 그 차이를 표현하기 위해서 현재 위치 cur 변수를 두었습니다

(1) cur변수에대해 왼쪽과, 오른쪽 벡터의 거리를 비교합니다.

마이너스쪽 거리와 플러스쪽 거리를 cur과 비교해서 왼쪽거리, 오른쪽 거리 변수를 지정합니다
여기서 왼쪽 거리가 더 작을 경우 (가까울 경우) 왼쪽을 택하고, cur는 왼쪽 벡터의 값을 가지게 됩니다
반대의 경우는 오른쪽 거리가 더 가까울 경우이므로, 오른쪽을 택합니다
가장 가까운 거리를 ans에 더합니다

if (i < minus.size())
	leftD = abs(minus[i] - cur);
if (j < plus.size())
	rightD = abs(plus[j] - cur);

(2) 포인터 옮기기
각 조건의 맞게 포인터를 옮겨줍니다 minus인 경우 i를, plus인 경우 j를 옮깁니다
벡터의 끝에 도달할 때까지 반복합니다

if (leftD <= rightD)
{
	ans += leftD;
	cur = minus[i];
	i++;
}
else
{
	ans += rightD;
	cur = plus[j];
	j++;
}

새롭게 알게 된 것

INT_MAX는 자주 썼는데 LLONG_MAX는 오랜만에 써봅니다 #include <climits>를 사용합니다!

전체 코드

#include <iostream>
#include <vector>
#include <algorithm>
#include <climits>

using namespace std;
typedef long long ll;

int main()
{
	int n;
	cin >> n;
	vector<ll> plus;

	vector<ll> minus;

	while (n--)
	{
		ll num;
		cin >> num;
		if (num > 0)
			plus.push_back(num);
		else
			minus.push_back(num);
	}

	sort(plus.begin(), plus.end());
	sort(minus.rbegin(), minus.rend());

	int i = 0, j = 0;
	ll ans = 0;
	ll cur = 0;

	while (i != minus.size() || j != plus.size())
	{

		ll leftD = LLONG_MAX;
		ll rightD = LLONG_MAX;

		if (i < minus.size())
			leftD = abs(minus[i] - cur);
		if (j < plus.size())
			rightD = abs(plus[j] - cur);

		if (leftD <= rightD)
		{
			ans += leftD;
			cur = minus[i];
			i++;
		}
		else
		{
			ans += rightD;
			cur = plus[j];
			j++;
		}
	}

	cout << ans;
}

while (i != minus.size() || j != plus.size())
{

ll leftD = LLONG_MAX;

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

수고하셨습니다!
longlong_max를 사용하신 이유가
왼쪽이나 오른쪽에 더 이상 후보가 없는 경우 엄청 큰 값을 넣어 둬서 이후 거리 비교 때 반대쪽이 선택 되도록 하신 건가요??

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants