//找到该数的左边界 intleft(int x) { int l = 0, r = n - 1, mid = l + r >> 1; while(l < r) { mid = l + r >> 1; if(a[mid] < x) l = mid + 1; else r = mid; } if(a[l] != x) l = -1; return l; } //找到该数的右边界 intright(int x) { int l = 0, r = n - 1, mid = l + r + 1 >> 1; while(l < r) { mid = l + r + 1 >> 1; if(a[mid] > x) r = mid - 1; else l = mid; } if(a[r] != x) r = -1; return r; }
利用STl
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
intmain() { cin >> n >> q; for(int i = 0; i < n; i++) cin >> a[i]; while(q--) { int x; cin >> x; int p1 = lower_bound(a, a + n, x) - a; int p2 = upper_bound(a, a + n, x) - a - 1; if(a[p1] != x) p1 = -1; if(a[p2] != x) p2 = -1; cout << p1 << " " << p2 << '\n'; } return0; }
浮点数二分
1 2 3 4 5 6 7
double l = -1e4, r = 1e4, mid; while(r - l > 1e-8) { mid = (l + r) / 2 ; if(a[mid] < n) l = mid; else r = mid; }