Obviously, you can perform binary search. Pay attention to the accuracy.
I know two ways to write binary statements. Pay attention to loop control.
First
# Include <iostream>
# Include <algorithm>
# Include <math. h>
Using Namespace STD;
Double Cal ( Double X)
{
Return 8 * X + 7 * X + 2 * X +3 * X + 6 ;
}
Int Main ()
{
Double Y;
Int T;
Scanf ( " % D " , & T );
While (T --)
{
Scanf ( " % Lf " , & Y );
If (Y <CAL ( 0 ) | Y> CAL ( 100 ))
{
Printf ( " No solution! \ N " );
Continue ;
}
Double Left = 0 , Right = 100 ;
While (Left <right)
{
Double Mid = (left + right )/ 2.0 ;
Double Temp = CAL (MID );
If (FABS (temp-y) <= 1E- 6 )
{
Printf ( " %. 4f \ n " , Mid );
Break ;
}
Else If (Temp> Y)
Right = mid;
Else Left = mid;
}
}
Return 0 ;
}
Second
# Include <iostream>
# Include <math. h>
Using Namespace STD;
Double Y = 0 ;
Double Cal ( Double X)
{
Return 8 * X + 7 * X + 2 * X + 3 * X + 6 ;
}
Int Main ()
{
Int T;
Scanf ( " % D " , & T );
While (T --)
{
Scanf ( " % Lf " , & Y );
If (CAL ( 0 )> Y | CAL ( 100 ) <Y)
{
Printf ( " No solution! \ N " );
Continue ;
}
Double Left = 0.0 , Right = 100.0 ;
While (Right-left> 1E- 6 )
{
Double Mid = (left + right )/2.0 ;
Double Temp = CAL (MID );
If (Temp> Y)
Right = mid-1E- 6 ;
Else
Left = Mid + 1E- 6 ;
}
Printf ( " %. 4lf \ n " , (Left + right )/ 2.0 );
}
Return 0 ;
}
Hdu2899 follows a similar question, but it is okay to first find the guide.
Hdu2899
# Include <iostream>
# Include <algorithm>
# Include <math. h>
Using Namespace STD;
Double Y;
Double Cal ( Double X)
{
Return 42 * POW (X, 6 ) + 48 * POW (X, 5 ) + 21 * X + 10 * X;
}
Double FX ( Double X)
{
Return 6 * POW (X, 7 ) +8 * POW (X, 6 ) + 7 * POW (X, 3 ) + 5 * X-y * X;
}
Int Main ()
{
Int T;
Scanf ( " % D " , & T );
While (T --)
{
Scanf ( " % Lf " , & Y );
Double Left = 0 , Right = 100 , Temp;
While (Left <right)
{
Double Mid = (left + right )/ 2.0 ;
Temp = CAL (MID );
If (FABS (temp-y) <= 1E- 5 )
{
Printf ( " %. 4f \ n " , FX (MID ));
Break ;
}
Else If (Temp <Y)
Left = mid;
Else Right = mid;
}
}
Return 0 ;
}
Hdu1551 cable master
How many cables are known, and the number of equal cables to be cut, and the maximum length of the cut Cables
If the length of the obtained cable is less than 0.01, the output is 0.0
Analysis: the length of the cable to be split into two parts can be approached.
Hdu1551
# Include <iostream>
# Include <math. h>
# Include <algorithm>
Using Namespace STD;
Int N, K;
Double A [ 10001 ], Maxlen;
Int Cal (Double C)
{
Int T = 0 ;
For ( Int I = 0 ; I <n; I ++)
T + = ( Int ) (A [I]/C );
Return T;
}
Int Main ()
{
While (Scanf (" % D " , & N, & K) = 2 & (N | K ))
{
Maxlen = 0.0 ;
For ( Int I = 0 ; I <n; I ++)
{
Scanf ( " % Lf " , & A [I]);
Maxlen = max (maxlen, a [I]);
}
Double Left = 0.01 , Right = maxlen, mid;
While (Right-left> 1E- 5 )
{
Mid = (left + right )/ 2 ;
Int T = CAL (MID );
If (T> = K)
Left = mid;
Else Right = mid;
}
Int T = CAL (left );
If (T> = K)
Printf ( " %. 2f \ n " , Left );
Else Printf ( " 0.0 \ n " );
}
Return 0 ;
}