- 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;
}

'APS > 백준' 카테고리의 다른 글

[2512] 예산 C++  (0) 2022.02.09
[1920] 수 찾기 C++  (0) 2022.02.08
[단계별로 풀어보기] 백트래킹  (0) 2021.08.20
[단계별로 풀어보기] 브루트 포스  (0) 2021.08.16
[단계별로 풀어보기] 재귀  (0) 2021.08.16

+ Recent posts