10
5 12 7 10 8 9 1 2 3 11
13
배열을 입력받고 먼저 오른차순으로 정렬시킨다.
1 2 3 5 7 8 9 10 11 12
n개의 서로 다른 양의 정수라고 했기 때문에 양 쪽 두 숫자를 더해서 13이 나오면 더 이상 그 숫자 중 하나와 다른 숫자를 더해서 13이 나오는 경우는 없으므로 양쪽에서 한칸씩 가운데쪽으로 당기면 된다.
5+9=14인 경우, x=13보다 큰 수가 나왔기 때문에 high--를 해줘야 한다. 왜냐하면 이미 합의 결과가 x보다 큰 수이기 때문에 이미 뽑은 숫자들보다 작은 숫자가 필요하기 때문이다.
반대로 x보다 작은 수가 나올때도 마찬가지.
#include <iostream>
#include <cmath>
#include <algorithm>
using namespace std;
int main(int argc, char* argv[])
{
int n;
scanf("%d", &n);
int* arr = new int[n];
for (int i = 0; i < n; i++)
scanf("%d", arr + i);
int x;
scanf("%d", &x);
sort(arr, arr + n);
int low = 0, high = n - 1;
int count = 0;
while (low < high)
{
int sum = arr[low] + arr[high];
if (sum == x)
{
low++;
high--;
count++;
}
else if (sum > x)
high--;
else
low++;
}
printf("%d", count);
return 0;
}