2 con trỏ

PHOTO EMBED

Mon Aug 26 2024 23:33:55 GMT+0000 (Coordinated Universal Time)

Saved by @LizzyTheCatto

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

int main() {
    ios_base::sync_with_stdio(0);
    cin.tie(NULL);

    int n;
    cin >> n;
    
    vector<int> a(n), b(n);
    
    for (int i = 0; i < n; ++i) {
        cin >> a[i];
    }
    
    for (int i = 0; i < n; ++i) {
        cin >> b[i];
    }
    
    sort(a.begin(),a.end());
    sort(b.begin(),b.end());
    
    int ans = 1000000;
    int l = 0; int r = n-1;
    while(l < n && r >= 0){
        int DIFF = a[l] + b[r];
        ans = min(ans,abs(DIFF));
        if(ans == 0){
            break;
        }
        
        if(DIFF > 0){
            r--;
        }
        else{
            l++;
        }
    }
    cout << ans;
    return 0;
}
content_copyCOPY

https://www.programiz.com/cpp-programming/online-compiler/