Run Code
|
API
|
Code Wall
|
Misc
|
Feedback
|
Login
|
Theme
|
Privacy
|
Patreon
Pairs having sum equal to target
#include<bits/stdc++.h> using namespace std; #define F first #define S second int main(){ int t; cin >> t; while(t--){ int n, target; cin >> n >> target; vector<int> v(n); for(int j = 0; j < n; j++) cin >> v[j]; sort(v.begin(), v.end()); int ans = 0; int l_low = 0, l_high = 0, r_low = n-1, r_high = n-1; while(l_high <= r_low){ while(l_high < n && v[l_high] == v[l_low]) l_high ++; while(r_low >= 0 && v[r_low] == v[r_high]) r_low --; if(v[l_low] + v[r_high] == target){ int cnt_l = l_high - l_low; int cnt_r = r_high - r_low; if(v[l_low] == v[r_high]) ans += cnt_l*(cnt_l-1)/2; else ans += cnt_l*cnt_r; l_low = l_high, r_high = r_low; continue; } if(v[l_low] + v[r_high] < target) { l_low = l_high; r_low ++; continue; } if(v[l_low] + v[r_high] > target) { r_high = r_low; l_high --; continue; } assert(false); } cout << ans << '\n'; } return 0; }
run
|
edit
|
history
|
help
0
synowie abrahama
Dijkastra
СПКИ АП КЭП 3
Christopher-Stellar
HelloWorldExample
4149 coj WIP
MyStringv2
base and derr con
MINVEST
Policy based smart pointer