No Rules Rules

두 수의 합 (feat. 백준, 3273번) 본문

생활/코테

두 수의 합 (feat. 백준, 3273번)

개발하는 완두콩 2022. 8. 23. 18:35
728x90
반응형

두 수의 합
https://www.acmicpc.net/problem/3273

 

3273번: 두 수의 합

n개의 서로 다른 양의 정수 a1, a2, ..., an으로 이루어진 수열이 있다. ai의 값은 1보다 크거나 같고, 1000000보다 작거나 같은 자연수이다. 자연수 x가 주어졌을 때, ai + aj = x (1 ≤ i < j ≤ n)을 만족하는

www.acmicpc.net

 

반응형

 

// woohyeon.kim
// kim519620.tistory.com
#include <iostream>
#include <algorithm>
using namespace std;
int arr[100000];
int main() {
	ios::sync_with_stdio(false), cin.tie(NULL);
	register int N, X;
	cin >> N;
	for (register int n = 0; n < N; ++n)
		cin >> arr[n];
	cin >> X;
	sort(arr, arr + N);
	register int ans = 0, s = 0, e = N - 1;
	while (1) {
		if (s >= e)
			break;
		register int tmp = arr[s] + arr[e];
		if (tmp == X)
			++ans, ++s, --e;
		else if (tmp < X)
			++s;
		else
			--e;
	}
	cout << ans;
	return 0;
}
// *&)*@*
  1. 투포인터 알고리즘은 두개의 인덱스 (start, end 또는 low, high) 로 진행됩니다
  2. 앞과 뒤의 인덱스가 서로 반전될때까지 비교하는 방식입니다.
728x90
반응형

'생활 > 코테' 카테고리의 다른 글

부분합 (feat. 백준, 1806번)  (0) 2022.08.24
두 용액 (feat. 백준, 2470번)  (0) 2022.08.23
운동 (feat. 백준, 1956번)  (0) 2022.08.23
플로이드 (feat. 백준, 11404번)  (0) 2022.08.23
최단경로 (feat. 백준, 1753번)  (0) 2022.08.22
Comments