区间查找
http://acm.nefu.edu.cn/JudgeOnline/problemShow.php?problem_id=1540
Description
给定两个长度为 n 的数组 A 和 B,对于所有的 ai+bj 从小到大排序,并输出第 L 个到第 R 个数。
Input
第一行三个数 n,L,R。然后分别输入a[i]和b[i];
Output
输出第L个数到第R个数!
Sample Input
2 1 4
1 3
2 4
Sample Output
3 5 5 7
注意最后的数后面带1个空格!
Hint
1<=n<1e5;1<=L<=R<=n^2;R-L<1e5;1<=a[i],b[i]<=1e9;
题解:
先将a,b排序。二分数字,找出在L位置的数字,同理找出R位置的数字。
n2遍历一遍将[L、R]端点中间的数字加入到数组中,排序输出。因为a,b排序,所以当碰到大于端点值时直接跳出循环,实际复杂度为O(R-L)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn = 1e5 + 10;
int a[maxn], b[maxn], n;
ll L, R, Ln, Rn, Lm, Rm;//Ln、Rn代表第L,R位是数字,Lm、Rm代表与第L,R位相同是数字有几个
vector<int>ans;
bool judge(int x, ll f) {//判断x position 是否大于等于L,大于返回1,否则0
ll r = 0;
int p = 0;
for (int i = n - 1; i >= 0; i--) {
while (a[i] + b[p] <= x && p < n) p++;
r += p;
}
if (f <= r)return 1;
else return 0;
}
ll solve(ll f) {//二分查找数位置f对应的数是多少
ll l = a[0] + b[0], r = a[n - 1] + b[n - 1], mid;
ll num = -1;
while (l <= r) {
mid = (l + r) / 2;
if (judge(mid, f)) {
num = mid;
r = mid - 1;
}
else
l = mid + 1;
}
return num;
}
int main() {
scanf("%d%lld%lld", &n, &L, &R);
for (int i = 0; i < n; i++)scanf("%d", &a[i]);
for (int i = 0; i < n; i++)scanf("%d", &b[i]);
sort(a, a + n), sort(b, b + n);
Ln = solve(L), Rn = solve(R);
//printf("%lld %lld\n", Ln, Rn);
if (Ln == Rn) {
for (int i = 0; i <= int(R-L); i++)printf("%d ", Ln);
printf("\n");
return 0;
}
for (int i = 0; i < n; i++) {//把在Ln和Rn之间的数放入数组中,复杂度R-L
int p = upper_bound(b, b + n, Ln - a[i]) - b;
for (int j = p; j < n; j++) {
if (a[i] + b[j] >= Rn)break;
ans.push_back(a[i] + b[j]);
}
}
ll tmp = 0;
for (int i = 0; i < n; i++) tmp += upper_bound(b, b + n, Ln - a[i]) - b;//计算大于Ln的第一个数前边有多少个
Lm = tmp - L + 1;
Rm = R - L + 1 - Lm - ans.size();
//printf("%lld %lld\n", Lm, Rm);
for (int i = 0; i < Lm; i++)printf("%lld ", Ln);
sort(ans.begin(), ans.end());//排序,按迅顺序输出
for (int i : ans)printf("%d ", i);
for (int i = 0; i < Rm; i++)printf("%lld ", Rn);
printf("\n");
return 0;
}