[2019杭电多校第五场][hdu6624]fraction

题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=6624

题意为求最小的b满足$a*b^{-1}\equiv x(modp)$.

把式子化简一下:

$a\equiv b*x(modp)$

$a=b*x-p*y$

$\because 0<a<b$

$\therefore 0<b*x-p*y<b$

$0<b*x-p*y\Rightarrow \frac{p}{x}<\frac{b}{y}$

$b*x-p*y<b\Rightarrow \frac{b}{y}<\frac{p}{x-1}$

$\therefore \frac{p}{x}<\frac{b}{y}<\frac{p}{x-1}$

这样题目就转化成求最小的b,y满足上式。

如果当前$[\frac{p}{x},\frac{p}{x-1}]$之间有整数,则$b=\left \lfloor \frac{p}{x} \right \rfloor+1,y=1$。

如果没有则可以辗转相除来递归求解。

例如:p=11,x=7。

$\frac{11}{7}<\frac{b}{y}<\frac{11}{6}$

则化为真分数后在求倒数。

$\frac{6}{5}<\frac{y}{b-y}<\frac{7}{4}$

再次化为真分数后求倒数。

$\frac{4}{3}<\frac{b-y}{2*y-b}<5$

此时[4/3,5]内有整数,则回溯得到答案。

 1 #include<iostream>
 2 #include<cstdio>
 3 #include<cstring>
 4 #include<string>
 5 #include<algorithm>
 6 #include<queue>
 7 using namespace std;
 8 typedef long long ll;
 9 void f(ll a, ll b, ll c, ll d, ll& x, ll& y){
10     ll q = a / b + 1;
11     if (q <= c / d){
12         x = q;
13         y = 1;
14         return;
15     }
16     q--;
17     a -= q * b; c -= q * d;
18     f(d, c, b, a, y, x);
19     x += q * y;
20     return;
21 }
22 int main(){
23     int t;
24     scanf("%d", &t);
25     while (t--){
26         ll b, y, a, p, x;
27         scanf("%lld%lld", &p, &x);
28         f(p, x, p, x - 1, b, y);
29         a = b * x - y * p;
30         printf("%lld/%lld\n", a, b);
31     }
32     return 0;
33 }

 

posted @ 2019-08-18 16:16  祈梦生  阅读(309)  评论(0编辑  收藏  举报