본문 바로가기

코딩테스트/백준

[백준] 1253번 : 좋다

728x90
반응형


🔗문제 링크

https://www.acmicpc.net/problem/1253

 

1253번: 좋다

첫째 줄에는 수의 개수 N(1 ≤ N ≤ 2,000), 두 번째 줄에는 i번째 수를 나타내는 Ai가 N개 주어진다. (|Ai| ≤ 1,000,000,000, Ai는 정수)

www.acmicpc.net

👩‍💻코드

#include <iostream>
#include <algorithm>
#include <vector>
using namespace std;

int main(){
    ios::sync_with_stdio(false);
    cin.tie(NULL);
    cout.tie(NULL);
    
    int N;
    cin >> N;
    
    vector<int> A(N,0);
    for(int i=0; i<N; i++){
        cin >> A[i];
    }
    
    sort(A.begin(), A.end());
    
    int count = 0;
    
    for(int i=0; i<N; i++){
        long find = A[i];
        int start_index = 0;
        int end_index = N-1;
        
        while(start_index < end_index){
            if (A[start_index] + A[end_index] == find){
                if (start_index != i && end_index != i){
                    count++;
                    break;
                }else if (start_index == i){
                    start_index++;
                }else if (end_index == i){
                    end_index--;
                }
            } else if (A[start_index]+A[end_index] < find){
                start_index++;
            } else{
                end_index--;
            }
        }
    }
    
    cout << count << "\n";
}

✏️문제 풀이

Do it! 알고리즘 코딩테스 - C++ 편 : 기출 유형 분석부터 문제 풀이 비법까지!를 참고하였습니다.

[백준] 1940번 : 주몽[백준]  2018번 : 수들의 합 5 풀이를 참고해주세요.

 

위 두 문제와 투 포인터 알고리즘을 사용하는 것은 동일합니다.

배열을 정렬후 하나의 포인터는 앞에서부터 다른 하나의 포인는 뒤에서부터 시작합니다.

다만 주의 할 점은 자기 자신이 포함되는 경우는 제외해야 한다는 점입니다.

728x90
반응형

'코딩테스트 > 백준' 카테고리의 다른 글

[백준] 11003번 : 최솟값 찾기  (1) 2024.09.06
[백준] 12891번 : DNA 비밀번호  (0) 2024.09.05
[백준] 1940번 : 주몽  (0) 2024.03.02
[백준] 2018번 : 수들의 합 5  (2) 2024.02.29
[백준] 10986번 : 나머지 합  (1) 2024.02.09