BOJ 7453번: 합이 0인 네 정수

십학년·2025년 8월 1일

BOJ 문제 풀기 (C++)

목록 보기
23/38

문제 설명

합이 0인 네 정수의 쌍의 개수 구하기

🔗 문제 링크


핵심 아이디어

  • "A+B+C+D = 0" → "A+B = -(C+D)" 를 이용하기
  • lower bound와 upper bound를 이용하여 0을 만들 수 있는 쌍 세기

코드

#include <bits/stdc++.h>
using namespace std;

typedef long long ll;
int n;
ll a[4005];
ll b[4005];
ll c[4005];
ll d[4005];

int main(){
    ios::sync_with_stdio(0);
    cin.tie(0);
    
    cin >> n;
    for(int i = 0; i < n; i++) cin >> a[i] >> b[i] >> c[i] >> d[i];
    
    vector<ll> ab; vector<ll> cd;
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            ab.push_back(a[i] + b[j]);
        }
    }
    for(int i = 0; i < n; i++){
        for(int j = 0; j < n; j++){
            cd.push_back(c[i] + d[j]);
        }
    }
    sort(ab.begin(), ab.end()); sort(cd.begin(), cd.end());
    
    ll ans = 0;
    for(auto i : ab){
        ans += upper_bound(cd.begin(), cd.end(), -i) - lower_bound(cd.begin(), cd.end(), -i);
    }
    cout << ans;
}

‼️ 주의할 점

  • 오버플로우 발생하지 않게 int 대신 long long 이용
  • binary_search가 아니라 lower bound와 upper bound 이용해야 존재하는지 여부가 아닌, 개수를 셀 수 있음
profile
감자입니다

0개의 댓글