PS

[백준] 3273번 두 수의 합 (C++)

-minari- 2024. 10. 18. 21:39

 

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

 

문제 설명

n개의 숫자가 주어질 때 이 중 두개의 숫자를 뽑아 합이 x가 되도록 하는 경우가 총 몇 개인지를 출력하는 문제이다.

 

주요 로직

1. 투포인터 문제이다
-> n개의 숫자를 받아 정렬한 후, 두 개의 포인터로 탐색한다.

 

정답 코드

#include <bits/stdc++.h>

using namespace std;

int n,x,ret;
vector<int> v;

int main(){
	ios_base::sync_with_stdio(false);
	cin.tie(NULL); cout.tie(NULL);
	
	cin >> n;
	for(int i=0; i<n; i++){
		cin >> x;
		v.push_back(x);
	}
	cin >> x;
	
	sort(v.begin(), v.end());
	
	int low=0, high=n-1;
	while(low < high){
		int sum = v[low] + v[high];
		if(sum == x) ret++, low++, high--;
		else if(sum < x) low++;
		else if(sum > x) high--;
	}
	
	cout << ret << "\n";
	
	return 0;
}