給定 n 頭牛的距離,求有多少對牛的距離和 ≤ S。n ≤ 100,000。
a[i] + a[j] ≤ S:i 與 [i+1..j] 都合法,計數 += j-i,i++#include <cstdio>
#include <algorithm>
using namespace std;
const int MAXN = 1000005;
int a[MAXN];
int main() {
int n, S;
while (scanf("%d%d", &n, &S) == 2) {
int cnt = 0;
for (int i = 0; i < n; i++) {
int x; scanf("%d", &x);
if (x < S) a[cnt++] = x;
}
sort(a, a + cnt);
long long ans = 0;
for (int i = 0, j = cnt - 1; i < j; ) {
if (a[i] + a[j] <= S) {
ans += j - i;
i++;
} else {
j--;
}
}
printf("%lld\n", ans);
}
return 0;
}
x ≥ S 的元素,減少排序規模long long 存儲答案(最大約 5e9)