Processing math: 100%
Solutions of Number of pairs - MarisaOJ: Marisa Online Judge

Solutions of Number of pairs

Select solution language

Write solution here.


User Avatar vdgminh    Created at    1 likes

C++

KHÔNG KHUYẾN KHÍCH VIỆC CHÉP CODE VÀ ĐỌC LỜI GIẢI, CHỈ ĐỌC KHI BÍ


Ý tưởng

  • ta đặt biến l=0,r=n1 (base-0).

  • Ta đặt một biến đếm (cnt) bằng không,

  • chạy một vòng while cho đến khi lr.

  • nếu Al+Ar=X thì cnt+1,l+1,r1.

  • nếu Al+Ar<X thì l+1.

  • nếu Al+Ar>X thì r1.


CODE MẪU:

AC mà không hiểu thì vứt!

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

signed main(){
    ios::sync_with_stdio(0);
    cin.tie(0); cout.tie(0);
    int n, x; cin >> n >> x;
    vector<int> a(n);
    for(int i = 0; i < n; i++) cin >> a[i];
    int l = 0, r = n - 1, ans = 0;
    while(l < r){
        if(a[l] + a[r] == x){
            ans++;
            l++;
            r--;
        }
        else if(a[l] + a[r] < x) l++;
        else r--;
    }
    cout << ans << '\n';
    return 0;
}