자라는 개발자/문제풀이
백준 c++ 3273번 두 수의 합
자란다
2022. 1. 11. 22:03
728x90
반응형
3273번 두 수의 합
문제 풀이
#include <iostream>
#include <algorithm>
using namespace std;
void fast_io(void)
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
cout.tie(NULL);
}
int n, arr[100001], x, cnt = 0;
int main(void)
{
fast_io();
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
cin >> x;
sort(arr, arr + n);
int l = 0, r = n - 1;
while (l < r)
{
if (arr[l] + arr[r] == x)
cnt++, l++, r--;
else if (arr[l] + arr[r] > x)
r--;
else
l++;
}
cout << cnt;
}
시간제한을 보지않고 for 문 두개로 돌려서 풀었다가 틀렸다.
다른방법이 있는걸 알게되어 찾아보니 정렬후 쌍을 맞춰야 한다고 했다.
이분탐색같은 방법으로 해결했다.
728x90
반응형