1. 程式人生 > >Fibonacci Sequence URAL - 1133 (二分)

Fibonacci Sequence URAL - 1133 (二分)

題目 https://cn.vjudge.net/problem/URAL-1133

題意  給你斐波那契數的某兩項,求第n項

思路 暴力二分給的下標小的的第二項 用另一個驗證

#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll a[10000];
ll x1,x2,x3,y1,y2;
int ok(ll x)
{
    a[x1] = y1;
    a[x1+1] = x;
    for(ll i=x1+2;i<=x2;i++)
    {
        a[i] = a[i-1] + a[i-2];
        if(a[i] > 2e9) return 1;
        else if(a[i] < -2e9) return -1;
    }
    if(y2 < a[x2]) return 1;
    else if(y2 > a[x2]) return -1;
    return 0;
}
ll solve(ll x)
{
    a[x1] = y1,a[x1+1] = x;
    if(x3 > x1)
    {
        for(ll i=x1+2;i<=x3;i++)
        {
            a[i] = a[i-1] + a[i-2];
        }
        return a[x3];
    }
    else
    {
        for(ll i=x1-1;i>=x3;i--)
        {
            a[i] = a[i+2] - a[i+1];
        }
        return a[x3];
    }
}

int main()
{
    ll n,m,i,j;
    scanf("%lld%lld%lld%lld%lld",&x1,&y1,&x2,&y2,&x3);
    x1 += 3000,x2 += 3000,x3 += 3000;
    if(x1 > x2)
    {
        swap(x1,x2);
        swap(y1,y2);
    }
    ll l = -2e9,r = 2e9;
    while(r > l + 1)
    {
        ll mid = (l+r)/2;
        if(ok(mid) > 0)
        {
            r = mid;
        }
        else if(ok(mid) < 0)
        {
            cout<<mid<<endl;
            l = mid;
        }
        else
        {
            ll ans = solve(mid);
            printf("%lld\n",ans);
            break;
        }
    }
    return 0;
}