JZOJ 3793. 【NOIP2014模拟8.20】数字对

目录:


题目:

单击查看题目


分析:

这道题,明显数论题:
对于60%的数据,1 <= n <= 20000
正难则反(又称“更相减损术”)
给定(a,b),将其还原
唯一还原方法
若 a > b,则(a,b)-> (a-b, b)
若 b >= a,则(a,b) -> (a, b-a)
对于给定的n,枚举所有的i,模拟还原(n,i)
取其中最少步数为解

对于100%的数据,1 <= n <= 10^6
对于给定的n,枚举所有的i,模拟还原(n,i)
取其中最少步数为解,但如何加速模拟过程保证复杂度呢?
类比求gcd的辗转相除法
若 a > b,则(a,b)-> (a%b, b)
若 b >= a,则(a,b) -> (a, b%a)

时间复杂度:
O n l o g n


代码:

#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
#include<cmath>
#include<queue>
#define LL long long
using namespace std;
inline LL read() {
    LL d=0,f=1;char s=getchar();
    while(s<'0'||s>'9'){if(s=='-')f=-1;s=getchar();}
    while(s>='0'&&s<='9'){d=d*10+s-'0';s=getchar();}
    return d*f;
}
int ans=99999999;
int gcd(int x,int y)
{
    if(y==1) return x-1;
    if(x==0||y==0||x==y) return 99999999;
    return gcd(y,x%y)+x/y;
}
int main()
{     
    int n=read();
    ans=n-1;
    for(int i=2;i<=n;i++)
        ans=min(ans,gcd(n,i));
    printf("%d",ans);
    return 0;
}

猜你喜欢

转载自blog.csdn.net/qq_35786326/article/details/80990901