프로그래밍/백준(BOJ)

[백준(BOJ) / C++][Silver Ⅳ] 1940번 : 주몽

데굴데굴이 2024. 6. 17. 23:21
반응형

문제

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


풀이

정렬 알고리즘으로 계산하기 편하게 정렬한 후 start_point 하고 end_point 의 합을 M과 비교하며 크면 end_point를 줄이고 작다면 start_point를 올리며 만약 M과 같았을때 count에 1를 더하며 start_point, end_point 각각을 +1, -1을 해준다.


소스코드

 

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

int main() 
{
	ios::sync_with_stdio(false);
	cin.tie(NULL);
	cout.tie(NULL);
	
	int N, M;
	int count, start_point, end_point;
	
	cin >> N >> M;
	
	vector<int> A(N, 0);
	
	for(int i = 0; i < N; i++)
	{
		cin >> A[i];
	}
	
	sort(A.begin(), A.end());
	
	count = 0; 
	start_point = 0;
	end_point = N - 1;
	
	while(start_point < end_point)
	{
		if(A[start_point] + A[end_point] == M)
		{
			count++;
			start_point++;
			end_point--;
		}
		else if(A[start_point] + A[end_point] > M)
		{
			end_point--;
		}
		else
		{
			start_point++;
		}
	}
	
	cout << count << "\n";
	
	return 0;
}
반응형