您的位置:首页 > 其它

【扩展欧几里得】BAPC2014 I Interesting Integers (Codeforces GYM 100526)

2016-08-25 15:29 513 查看
题目链接:

  http://codeforces.com/gym/100526

  http://acm.hunnu.edu.cn/online/?action=problem&type=show&id=11672&courseid=0


题目大意:

  给定任意一个N,(N<=109)求斐波那契—卢卡斯数列的前两项A和B。(先满足B最小再满足A最小,A<=B)

  斐波那契—卢卡斯数列是斐波那契数列的推广,斐波那契数列f[0]=0,f[1]=1,斐波那契—卢卡斯数列f[0]=A,f[1]=B。

  二者均满足f[i]=f[i-1]+f[i-2],i>=2。

题目思路:

  【数论】【扩展欧几里得】

  首先如果数列S是斐波那契数列,则A*S,S+S也满足f[i]=f[i-1]+f[i-2]。

  那么考虑A=1,B=0的斐波那契—卢卡斯数列S1,为第一个数对最终答案的影响。

  同样,A=0,B=1的斐波那契—卢卡斯数列S2,为第二个数对最终答案的影响。

  容易得到这两个数列是错位的斐波那契数列

  S1=1,0,1,1,2,3,5...

  S2=0,1,1,2,3,5,8...

  S2[i]=S1[i+1].

  而把S1*A+S2*B如果能含有N,则A B的最小解即为所求。

  所以只需要求出斐波那契数列的前45项(109内),接下来就是枚举N是由斐波那契数列中哪两个相邻的数分别乘A和B得到的。

  即A*f[i]+B*f[i-1]=N。可以对f[i],f[i-1]扩展欧几里得,求出对应的A和B,看看能否把X,Y调成满足题意得(0<B<=A)如果行则为答案。

//
//by coolxxx
//#include<bits/stdc++.h>
#include<iostream>
#include<algorithm>
#include<string>
#include<iomanip>
#include<map>
#include<memory.h>
#include<time.h>
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
//#include<stdbool.h>
#include<math.h>
#define min(a,b) ((a)<(b)?(a):(b))
#define max(a,b) ((a)>(b)?(a):(b))
#define abs(a) ((a)>0?(a):(-(a)))
#define lowbit(a) (a&(-a))
#define sqr(a) ((a)*(a))
#define swap(a,b) ((a)^=(b),(b)^=(a),(a)^=(b))
#define mem(a,b) memset(a,b,sizeof(a))
#define eps (1e-8)
#define J 10
#define mod 1000000007
#define MAX 0x7f7f7f7f
#define PI 3.14159265358979323
#define N 54
using namespace std;
typedef long long LL;
int cas,cass;
int n,m,lll,ans;
int f
={1,0};
LL exgcd(LL a,LL b,LL &x,LL &y)
{
if(!b){x=1,y=0;return a;}
LL d=exgcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main()
{
#ifndef ONLINE_JUDGE
//	freopen("1.txt","r",stdin);
//	freopen("2.txt","w",stdout);
#endif
int i,j,k;
LL a,b,c,d,x,y,lcm,ii;
for(i=1;i<45;i++)
f[i+1]=f[i-1]+f[i];
for(scanf("%d",&cas);cas;cas--)
//	for(scanf("%d",&cas),cass=1;cass<=cas;cass++)
//	while(~scanf("%s",s+1))
//	while(~scanf("%d",&n))
{
scanf("%d",&n);
for(k=45;k && f[k]>n;k--);
if(f[k]==n)
{
puts("1 1");
continue;
}
for(i=k;i>2;i--)
{
a=f[i];b=f[i-1];c=n;
lcm=a*b;
d=exgcd(a,b,x,y);
x=x%b+b;
y=(1-x*a)/b;
x*=c;y*=c;
if(y<=0)
{
ii=(y-a+1)/(-a);
y+=ii*a;
x-=ii*b;
}
while((x-b)>=(y+a))x-=b,y+=a;
if(x<=0 || y<=0 || y>x)continue;
printf("%I64d %I64d\n",y,x);
break;
}
}
return 0;
}
/*
//

//
*/
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: