Luogu p3382 Rule of Thirds (Template)

The general idea of ​​three points:

By continuously narrowing the range of [L, R], we can get infinitely close to point A.
Method: First take the midpoint mid of [L, R], then take the midpoint mmid of [mid, R], and narrow the range by comparing the sizes of f(mid) and f(mmid).
When L=R-1 in the end, compare the values ​​of these two points, and we will find the answer.
1. When f(mid) > f(mmid), we can conclude that mmid must be to the right of point A.
Proof by contradiction: Assume that mmid is to the left of point A, then mid must also be to the left of point A. From f(mid) > f(mmid), it can be deduced that mmid < mid, which is inconsistent with the known, so the assumption is not valid.
Therefore, at this time, R = mmid can be used to narrow the range.
2. When f(mid) < f(mmid), we can conclude that mid must be to the left of point A.
Proof by contradiction: Assume that mid is on the right side of point A, then mmid must also be on the right side of point A. From f(mid) < f(mmid), it can be deduced that mid > mmid, which is inconsistent with the known, so the assumption is not valid.
In the same way, L = mid can be used to narrow the range.

Let’s look at the question again

Description of the problem
As in the title, an N-th degree function is given, ensuring that there is a point x in the range [l, r], such that [l, x] increases monotonically and [x, r] decreases monotonically. Try to find the value of x.

Input format
The first line contains a positive integer N and two real numbers l, r at a time, and the meaning is as shown in the title description.

The second line contains N + 1 real numbers, which from high to low represent the coefficients of each term of the N-th order function.

Output format
The output is one line, containing a real number, which is the value of x. If the relative or absolute error between your answer and the standard answer does not exceed 10^-5,
  it is considered correct.

Input and output example
Input 
3 -0.9981 0.5
1 -3 -3 1
Output
-0.41421
Instructions/Tips
For 100% of the data, 136≤N≤13, the function coefficients are all within [-100,100] and at most 15 decimal places, ∣l ∣,∣r∣≤10 and up to 15 decimal places. l≤r.

AC:

#include<bits/stdc++.h>
using namespace std;

const double dif=1e-7;
const int MAXN=13;

int n;
double coe[MAXN+5];

double check(double x)
{
	double temp=1.0,ans=0.0;
	for(int i=n;i>=0;i--,temp*=x) ans+=coe[i]*temp;
	return ans;
}

double Find(double L,double R)
{
	double Lmid,Rmid;
	while(L+dif<=R)
	{
		Lmid=L+(R-L)/3.0;
		Rmid=R-(R-L)/3.0;
		if(check(Lmid)>check(Rmid)) R=Rmid;
		else L=Lmid;
	}
	return (Lmid+Rmid)/2.0;
}

int main()
{
	double L,R;
	scanf("%d",&n),cin>>L>>R;
	for(int i=0;i<=n;i++) cin>>coe[i];
	printf("%.5lf\n",Find(L,R));
	//printf("%.5lf\n",check(-0.41421));
	return 0;
}

Guess you like

Origin blog.csdn.net/m0_74153798/article/details/130835025