본문 바로가기

개발/알고리즘

백준 주몽 1940 C++

문제

www.acmicpc.net/problem/1940

 

1940번: 주몽

첫째 줄에는 재료의 개수 N(1 ≤ N ≤ 15,000)이 주어진다. 그리고 두 번째 줄에는 갑옷을 만드는데 필요한 수 M(1 ≤ M ≤ 10,000,000) 주어진다. 그리고 마지막으로 셋째 줄에는 N개의 재료들이 가진 고

www.acmicpc.net

코드

#include<bits/stdc++.h>

using namespace std;

int t, sum, a[150001], cnt;

int main()
{
	ios_base::sync_with_stdio(false); 
	cin.tie(NULL); 
	cout.tie(NULL);
	
	cin >> t >> sum;

	for (int i = 0; i < t; i++)
	{
		cin >> a[i];
	}

	sort(a, a + t);

	int str = 0; 
	int end = t - 1;

	while (str < end)
	{
		if (a[str] + a[end] == sum)
		{
			cnt++;
			str++;
			end--;
		}
		else
		{
			if (a[str] + a[end] > sum)
			{
				end--;
			}
			else
			{
				str++;
			}
		}
	}

	cout << cnt << "\n";

	return 0;
}

 

걸린 시간

1시간

 

*투포인터 방식 문제를 처음 풀어봄. 투포인터 알고리즘 원리 이해하느라 시간이 조금 걸림.