Dat je niz celih brojeva \(a_1, a_2, \ldots, a_n\), i dva cela broja \(L\) i \(R\) (\(L \leq R\)). Potrebno je izračunati broj parova indeksa \((i, j)\) tako da \(1 \leq i < j \leq n\) i \(L \leq a_j - a_i \leq R\).
Sa standardnog ulaza se unosi broj elemenata \(n\) (\(1 \leq n \leq N\)) niza \(a\). Nakon toga, unosi se \(n\) elemenata niza \(a\) (\(-10^9 \leq a_i \leq 10^9\)). Na kraju, unose se celi brojevi \(L\) i \(R\) (\(-10^9 \leq L < R \leq 10^9\)).
Ispisati ukupan broj parova indeksa \((i, j)\) za koje važe uslovi zadatka.
5 1 5 3 9 7 2 4
5
Važeći parovi i razlike odgovarajućih elemenata niza:
4 2 2 2 2 0 0
6
U ovom bloku se opisuje glavno rešenje zadatka.
#include <iostream>
#include <vector>
using namespace std;
int count_leq(vector<int> &a, vector<int> &tmp,
const int K, const int l, const int r)
{
if (l >= r) {
return 0;
}
int count = 0;
int m = (l + r) / 2;
// sort + count
+= count_leq(a, tmp, K, l, m);
count += count_leq(a, tmp, K, m + 1, r);
count
// count sorted
int j = m + 1;
for (int i = l; i <= m; i++) {
while (j <= r && a[j] - a[i] <= K) {
++;
j}
+= j - (m + 1);
count }
// merge sorted
int i = l, k = l; j = m + 1;
while (i <= m || j <= r) {
if (a[i] <= a[j]) {
[k++] = a[i++];
tmp} else {
[k++] = a[j++];
tmp}
}
while (i <= m) {
[k++] = a[i++];
tmp}
while (j <= r) {
[k++] = a[j++];
tmp}
for (int p = l; p <= r; p++) {
[p] = tmp[p];
a}
return count;
}
int count_leq(vector<int> a, const int K)
{
const int n = a.size();
<int> tmp(n);
vectorreturn count_leq(a, tmp, K, 0, n - 1);
}
int count_range(vector<int> &a, const int L, const int R)
{
return count_leq(a, R) - count_leq(a, L - 1);
}
int main()
{
int n; cin >> n;
<int> a(n);
vectorfor (int i = 0; i < n; i++) {
>> a[i];
cin }
int L, R; cin >> L >> R;
<< count_range(a, L, R) << endl;
cout
return 0;
}
#include <iostream>
#include <vector>
using namespace std;
int main()
{
int n; cin >> n;
<int> a(n);
vectorfor (int i = 0; i < n; i++) {
>> a[i];
cin }
int L, R; cin >> L >> R;
int count = 0;
for (int i = 0; i < n - 1; i++) {
for (int j = i + 1; j < n; j++) {
int dist = a[j] - a[i];
if (L <= dist && dist <= R) {
++;
count}
}
}
<< count << endl;
cout
return 0;
}