HDU-6624 (杭电多校第5场 fraction)辗转相除

题意:给定x和p,求一个最小的b使得存在一个a<b 并且a \equiv b x(\bmod p)

题解:由于a \equiv b x(\bmod p) , 那么 \exists y>0, bx-a=py , 于是0<a=bx-py<b ,从而\frac{p}{x}<\frac{b}{y}<\frac{p}{x-1} 。那么我们就是要求一个最小的b,这就可以通过辗转相除(出题人管这叫辗转相除):

Let's consider we are solving problem for \left[\frac{p_{1}}{q_{1}}, \frac{p_{2}}{q_{2}}\right] .

Here are three cases:

  1. \frac{p_{1}}{q_{1}} \geq 1. Let's subtract \left\lfloor\frac{p_{1}}{q_{1}}\right\rfloor from both numbers. Obviously, solution is same up to adding it back.

  2. \frac{p_{1}}{q_{1}}<1<\frac{p_{2}}{q_{2}}. then 1/1 is answer! Note, that it minimize both parts of fraction.

  3. \frac{p_{2}}{q_{2}} \leq 1. Let's solve for \left[\frac{q_{2}}{p_{2}}, \frac{q_{1}}{p_{1}}\right]. This is the same problem (up to answer inverse), but now we need, to minimize numerator, not denominator. But this doesn't matter, because step 2 optimize both!

——PavelKunyavskiy’ s comment :https://codeforces.com/blog/entry/67091?#comment-512389

btw, 出题人提到这个算法来自于 Code Jam 2019 Round 2 - New Elements Part 2 ,上述的算法描述也是这么找的

#include <bits/stdc++.h>
using namespace std;

using ll = long long;
using pll = pair<ll, ll>;

pll find_best(pll l,pll r){
    if(l.first>=l.second){
        ll fl = l.first / l.second;
        pll res = find_best({l.first - fl * l.second, l.second}, {r.first - fl * r.second, r.second});
        res.first += res.second * fl;
        return res;
    }
    if(r.first>r.second){
        return {1, 1};
    }
    pll res = find_best({r.second, r.first}, {l.second, l.first});
    return {res.second, res.first};
}

int main()
{
    ios::sync_with_stdio(false);
    int round;
    cin >> round;
    while (round--)
    {
        ll p, x;
        cin >> p >> x;
        auto res = find_best({p, x}, {p, (x - 1)});
        ll b = res.first;
        ll y = res.second;
        cout << (b * x - p * y) << "/" << b << endl;
    }
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • rljs by sennchi Timeline of History Part One The Cognitiv...
    sennchi阅读 7,458评论 0 10
  • The Inner Game of Tennis W Timothy Gallwey Jonathan Cape ...
    网事_79a3阅读 12,333评论 3 20
  • **2014真题Directions:Read the following text. Choose the be...
    又是夜半惊坐起阅读 9,968评论 0 23
  • 今天发现一个道理,“天道好轮回不信抬头看苍天饶过谁” 做错事总会被惩罚,你伤害一个人,就会跳出另一个人来伤害你。好...
    辣条配泡芙阅读 442评论 0 0
  • 我正坐等早茶, 不太熟练的用功夫茶茶具喝普洱,和隔桌共用一个酒精炉加热水,默契地最后喝完的一桌找服务员添水。汕头喝...
    E墨瞳阅读 215评论 0 0