二分查找(二分+递推)

http://poj.org/problem?id=1759

题意:有一个花环,旁边挂灯泡,总共n个灯泡,第Hi个灯泡的高度是H(i+1) 和 H(i-1)高度的平均值减1.
H1 = A
Hi = (H i-1 + H i+1)/2 - 1, for all 1 < i < N
HN = B
Hi >= 0, for all 1 <= i <= N
现在给出总共灯泡的个数n,以及第一个灯泡的高度,求最右边的灯泡的最低高度。
解法:将递推式转变一下,Hi = 2*Hi-1 + 2 - Hi-2 .可知Hi 与 Hi-1成正相关。也可知Hn与H2成正相关。

所以二分找满足条件的H2的最小值,对应递推的Hn

//#include<bits/stdc++.h>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <algorithm>
#include <iostream>
#include <string>
#include <stdio.h>
#include <queue>
#include <stack>
#include <map>
#include <set>
#include <string.h>
#include <vector>
typedef long long ll ;
#define int ll
#define mod 1000000007
#define gcd __gcd
#define rep(i , j , n) for(int i = j ; i <= n ; i++)
#define red(i , n , j)  for(int i = n ; i >= j ; i--)
#define ME(x , y) memset(x , y , sizeof(x))
//ll lcm(ll a , ll b){return a*b/gcd(a,b);}
//ll quickpow(ll a , ll b){ll ans=1;while(b){if(b&1)ans=ans*a%mod;b>>=1,a=a*a%mod;}return ans;}
//int euler1(int x){int ans=x;for(int i=2;i*i<=x;i++)if(x%i==0){ans-=ans/i;while(x%i==0)x/=i;}if(x>1)ans-=ans/x;return ans;}
//const int N = 1e7+9; int vis[n],prime[n],phi[N];int euler2(int n){ME(vis,true);int len=1;rep(i,2,n){if(vis[i]){prime[len++]=i,phi[i]=i-1;}for(int j=1;j<len&&prime[j]*i<=n;j++){vis[i*prime[j]]=0;if(i%prime[j]==0){phi[i*prime[j]]=phi[i]*prime[j];break;}else{phi[i*prime[j]]=phi[i]*phi[prime[j]];}}}return len}
#define INF  0x3f3f3f3f
#define PI acos(-1)
#define pii pair<int,int>
#define fi first
#define se second
#define lson l,mid,root<<1
#define rson mid+1,r,root<<1|1
#define pb push_back
#define mp make_pair
#define cin(x) scanf("%lld" , &x);
using namespace std;
const int N = 1e7+9;
const int maxn = 1e5+9;
const double esp = 1e-2;
int n;
double a ;
double b[4];
double ans;

bool check(double x){
    b[1] = a ;
    b[2] = x ;
    for(int i = 3 ; i <= n ; i++){
        b[3] = (2.0*b[2]+2) - b[1];
        b[1] = b[2];
        b[2] = b[3];
        if(b[3] < 0) return false;
    }
    ans = b[3];
    return true;
}

void solve(){
    double l = 0 , r = a ;
    for(int i = 0 ; i < 100 ; i++){
        double mid = (l + r) / 2 ;
        if(check(mid)) r = mid ;
        else l = mid ;
    }
    printf("%.2f\n" , ans);
}

signed main()
{
    //ios::sync_with_stdio(false);
    //cin.tie(0); cout.tie(0);
    //int t ;
    //cin(t);
    //while(t--){
    while(~scanf("%lld%lf" , &n , &a))
        solve();
    //}
}

 

posted @ 2020-03-10 17:30  无名菜鸟1  阅读(725)  评论(0编辑  收藏  举报