APS/백준

[3273] 두 수의 합

문래동까마귀 2021. 8. 25. 12:57

- Test1. 답은 맞으나 시간초과

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

int n,x;
int arr[100000];
int path[2];
int cnt = 0;

void run(int le, int st) {

    if (le == 2) {
        if (path[0] + path[1] == x)  cnt++;
        return;
    }

    for (int i = st; i < n; i++) {
        path[le] = arr[i];
        run(le + 1, i + 1);
    }
}

int main() {
    cin >> n;

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

    cin >> x;
    
    run(0,0);

    cout << cnt;
    return 0;
}

- Test2. 정렬후 처음과 끝의 합이 찾는값보다 크거나 작으면 s++, e--

#include<iostream>
#include<algorithm>
#include<vector>

using namespace std;

int n,x;
int arr[100000];
int cnt = 0;

int main() {
    cin >> n;

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

    cin >> x;
    
    sort(arr, arr + n);
    
    int start = 0, end = n - 1;
    int sum;
    while(start<end) {
        sum = arr[start] + arr[end];
        if (sum == x) {
            cnt++;
            start++;
            end--;
        }
        else if (sum > x) end--;
        else if (sum < x) start++;
    }

    cout << cnt;
    return 0;
}