Series: Algorithms
cpp
43 lines
· Updated 2026-04-04
greedy_sort.cpp
Algorithms/greedy_sort.cpp
// Greedy Algorithm
// 排序 + 雙指針 / HashMap — O(N log N)
#include <iostream>
#include <vector>
#include <algorithm>
using namespace std;
int main() {
int n;
long long C;
// Read input until EOF
while (cin >> n >> C) {
vector<long long> a((size_t)n);
for (size_t i = 0; i < (size_t)n; i++) {
cin >> a[i];
}
// Step 1: copy the array and sort it.
vector<long long> sorted_a = a;
sort(sorted_a.begin(), sorted_a.end());
// Step 2: use two pointers to find the number of pairs (i, j) such that a[i] - a[j] == C
long long ans = 0;
for (size_t j = 0; j < (size_t)n; j++) {
long long target = sorted_a[j] + C;
// lower_bound: find the first element in sorted_a that is less than or equal to target
// upper_bound: find the first element in sorted_a that is greater than target
auto lo = lower_bound(sorted_a.begin(), sorted_a.end(), target);
auto hi = upper_bound(sorted_a.begin(), sorted_a.end(), target);
ans += hi - lo;
}
cout << ans << endl;
}
return 0;
}
Related articles
Algorithms
java
Updated 2026-03-02
#include <iostream>.java
#include <iostream>.java — java source code from the Algorithms learning materials (Algorithms/#include <iostream>.java).
Read article →
Algorithms
cpp
Updated 2026-04-07
748.cpp
748.cpp — cpp source code from the Algorithms learning materials (Algorithms/748.cpp).
Read article →
Algorithms
cpp
Updated 2026-04-07
827.cpp
827.cpp — cpp source code from the Algorithms learning materials (Algorithms/827.cpp).
Read article →
Algorithms
cpp
Updated 2026-04-07
827_best_greedy.cpp
827_best_greedy.cpp — cpp source code from the Algorithms learning materials (Algorithms/827_best_greedy.cpp).
Read article →
Algorithms
cpp
Updated 2026-04-07
8402.cpp
8402.cpp — cpp source code from the Algorithms learning materials (Algorithms/8402.cpp).
Read article →
Algorithms
cpp
Updated 2026-04-07
860.cpp
860.cpp — cpp source code from the Algorithms learning materials (Algorithms/860.cpp).
Read article →