int type of binary search
The basic idea : half basic idea is to find a time to find the narrow half Look
int LowerBound(int a[], int target, int left, int right)
{
while(right >= left)
{
int mid = left + (right - left) / 2;//防止left + right导致上溢
if(a[mid] > target) right = mid - 1;
else if(a[mid] < target) left = mid + 1;
else if(a[mid] == target) return mid;
}
return -1;
}
In order to prevent the occurrence of overflow left + right, can be exchanged for left + (right - left) / 2
Trying to find examples where the array element position
#include <stdio.h>
int LowerBound(int a[], int target, int left, int right)
{
while(right >= left)
{
int mid = left + (right - left) / 2;//防止left + right导致上溢
if(a[mid] > target) right = mid - 1;
else if(a[mid] < target) left = mid + 1;
else if(a[mid] == target) return mid;
}
return -1;
}
int main(void)
{
int a[105] = {1, 2, 3, 4, 5, 6, 7, 8, 9, 10};
int ans;
ans = LowerBound(a, 11, 0, 9);
if(ans >= 0) printf("%d", ans);
else printf("NO");
return 0;
}
a double binary search
Int type and similar, the only difference is the type double
while - (right left> 0.0000001)
function tz example of big brother
Topic background
tz chiefs from distant Himalayas dug up a NN-order functions, in order to study the magic of the function, tzdalao the functions delegated to the programming club.
Input Format
The first line, a positive integer N and two real numbers ll, rr, showing the closed interval range.
Second row, N + 1N + 1 real number, from left to right represents the coefficients of the functions.
Output Format
Output value of x, rounded to five decimal places.
Sample input
3 -0.9981 0.5
1 -3 -3 1
Sample Output
-0.41421
Explanation
=. 3 above sample n-, X . 3 - 3x 2 - 3x +. 1
Problem-solving ideas: talk coefficients derivation function into an array, using the dichotomy to find a derivative is zero point
AC Code
include <stdio.h>
#include <math.h>
double a[100] = {0}, n, ans1, mid;
double y(double x)//判断一阶导数的大小
{
double j = n-1, ans = 0;
for(int i = 0 ; i < n && j >= 0; i++, j--)
{
ans += a[i]*pow(x, j);
}
return ans;//返回一阶导数的值
}
int main(void)
{
double temp;
double l, r;
scanf("%lf%lf%lf", &n, &l, &r);
temp = n;
for(int i = 0; i <= n; i++)
{
scanf("%lf", &a[i]);
a[i] = a[i]*temp;//求一阶导数的系数
temp -= 1;
}
while(r - l > 0.0000001)。。二分查找
{
mid = (r+l)*1.0/2;
if(y(mid) > 0) l = mid;
else r = mid;
}
printf("%.5lf", mid);
return 0;
}