P2090 数字对

P2090 数字对

不是,这不是黄题吗,鉴定为我太菜了

考虑这东西长得像辗转相除法。最终结果一定是 \((n,B)\) 这样子的。那么它一定是由 \((n-B,B)\) 转移过来。对于 \((a,b)\) 如果 \(a>b\) 它会变成 \((a-b,b)\),否则是 \((a,b-a)\)

于是也许我们可以枚举 \(B\),把 \(a-b\) 这个操作变成 \(a\bmod b\) 这样时间就是 \(O(n\log n)\) 了。

#include<bits/stdc++.h>
// #define LOCAL
#define sf scanf
#define pf printf
#define rep(x,y,z) for(int x=y;x<=z;x++)
using namespace std;
typedef long long ll;
const int N=1e6+7,inf=0x3f3f3f3f;
int n;
int ans=inf;
int cal(int a,int b){
    if(a<b) swap(a,b);
    if(b==1) return a-1;
    if(b==0) return inf;
    return cal(a%b,b)+a/b;
}
int main(){
    #ifdef LOCAL
    freopen("in.txt","r",stdin);
    freopen("my.out","w",stdout);
    #endif
    sf("%d",&n);
    rep(B,1,n){
        ans=min(ans,cal(n,B));
    }
    pf("%d\n",ans);
}
posted @ 2024-09-27 13:26  wing_heart  阅读(9)  评论(0)    收藏  举报