在本题中:
左端点的判断条件是mid>=x,因为是升序的,如果成立,说明左端点l只会在mid上或mid左侧。 将右端点调整为mid,这样mid只会不变或变小。 现在变小了,说明目前的l并非答案的左区间,中间掺杂了更小的数列,此时需要使左区间l+1。 左端点是通过l查找,l从0累加,不会产生遗漏。 左端点确定之后,右端点从n-1,也就是最右端开始,累减,确定答案的右端点。
#include<cstdio>
#include<cstring>
#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
const int N = 100000;
int n, m;
int q[N];
int main() {
scanf("%d%d", &n, &m);
for (int i = 0; i < n; i++) scanf("%d", &q[i]);
for (int i = 0; i < m; i++) {
int x;
scanf("%d", &x);
int l = 0, r = n - 1;
while (l < r) {
int mid = l + r >> 1;
if (q[mid] >= x)r = mid;
else l = mid + 1;
}
if (q[r] == x) {
cout << r << " ";
r = n - 1;
while (l < r) {
int mid = l + r + 1 >> 1;
if (q[mid] <= x)l = mid;
else r = mid - 1;
}
cout << l << endl;
} else cout << "-1 -1" << endl;
}
}
这里求二分之一不能用位移,因为是浮点数。
#include <iostream>
#include <cstdio>
using namespace std;
double x;
int main() {
cin >> x;
double l = -100000, r = 100000;
while (r - l > 1e-8) {
double mid = (l + r) / 2;
if (mid * mid * mid < x) l = mid;
else r = mid;
}
printf("%.6f", r);
return 0;
}
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 100010;
int n, m;
int a[N], s[N];
int main() {
scanf("%d%d", &n, &m);
for (int i = 1; i <= n; i++) {
scanf("%d", a + i);
s[i] = s[i - 1] + a[i];
}
while (m--) {
int l, r;
scanf("%d%d", &l, &r);
printf("%d\n", s[r] - s[l - 1]);
}
return 0;
}
如何计算前缀和矩阵?
如何利用前缀和矩阵,计算子矩阵的和?
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 1e3 + 10;
int n, m, q;
int a[N][N], s[N][N];
int main() {
scanf("%d%d%d", &n, &m, &q);
for (int i = 1; i <= n; i++) {
for (int j = 1; j <= m; j++) {
scanf("%d", &a[i][j]);
s[i][j] = s[i - 1][j] + s[i][j - 1] - s[i - 1][j - 1] + a[i][j];
}
}
while (q--) {
int x1, y1, x2, y2;
scanf("%d%d%d%d", &x1, &y1, &x2, &y2);
printf("%d\n", s[x2][y2] - s[x1 - 1][y2] - s[x2][y1 - 1] + s[x1 - 1][y1 - 1]);
}
return 0;
}