fork download
  1. #include <bits/stdc++.h>
  2.  
  3. using namespace std;
  4.  
  5. typedef long long ll;
  6. typedef pair<int, int> ii;
  7.  
  8. const int INF = 1e9;
  9. const ll LINF = 1e18;
  10.  
  11. const int N = 5e3 + 5;
  12.  
  13. int n;
  14. int a[N];
  15.  
  16. int main() {
  17. ios::sync_with_stdio(false);
  18. cin.tie(nullptr);
  19. cin >> n;
  20. for (int i = 1; i <= n; i++) cin >> a[i];
  21.  
  22. sort(a + 1, a + n + 1);
  23.  
  24. // a[k] < a[i] + a[j] (i < j < k)
  25. ll ans = 0;
  26. for (int i = 1; i <= n; i++) {
  27. for (int j = i + 1, k = i + 1; j <= n; j++) {
  28. // k là vị trí lớn nhất thoả mãn a[k] < a[i] + a[j]
  29. while (k + 1 <= n && a[k + 1] < a[i] + a[j]) k++;
  30. ans += k - j;
  31. }
  32. }
  33.  
  34. cout << ans << '\n';
  35. }
Success #stdin #stdout 0s 5288KB
stdin
5
4 3 1 5 7 
stdout
3