裴蜀定理
裴蜀定理
如果 a,b 均是正整数且互质,那么由 ax+by,x≥0,y≥0 不能凑出的最大数是 ab−a−b。
证明
(根据y总的思路)
首先证明 ab−a−b 不能被 ax+bx,x≥0,y≥0表示出。
反证法,假设 ab−a−b=ax+by,那么ab=a(x+1)+b(y+1),由于a|ab,a|a(x+1),所以 a|b(y+1),由于 a,b互质,所以 a|(y+1),由于y≥0,所以 a<=y+1,所以 b(y+1)≥ab。同理可得 a(x+1)≥ab,所以a(x+1)+b(y+1)≥2ab>ab,矛盾。
还可以参考这篇博客。
例题
AcWing 1205. 买不到的数目
先打表
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
bool dfs(int m,int p,int q)
{
if(m==0) return true;
if(m>=p && dfs(m-p,p,q)) return true;
if(m>=q && dfs(m-q,p,q)) return true;
return false;
}
int main()
{
int p,q;
cin>>p>>q;
int res=0;
for (int i = 1; i <= 1000; i ++ )
{
if(!dfs(i,p,q)) res=i;
}
cout<<res<<endl;
return 0;
}
但是上述代码会TLE,接下来直接用裴蜀定理。
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int p,q;
cin>>p>>q;
cout << p*q-p-q<<endl;
return 0;
}
完美AC!
AcWing 525. 小凯的疑惑
本题数据量较大 所以开long long,也是直接套定理。
//裴蜀定理
#include <iostream>
#include <cstring>
#include <algorithm>
typedef long long LL;
using namespace std;
int main()
{
LL a,b;
cin>>a>>b;
cout << a*b-a-b<<endl;
return 0;
}
总结
计算 ab−a−b的时间复杂度是 O(1)。
结论:如果 a,b 均是正整数且互质,那么由 ax+by,x≥0,y≥0 不能凑出的最大数是 ab−a−b。