[exgcd] Jzoj P5855 吃蛋糕
题解
- 其实就是求ax+by=c的非负整数解
- 显然exgcd
- 先判断其是否有解,设a'=a/d,b'=b/d,c'=c/d
- 之后模拟求出所有解个数,即x+=b,y-=a
- 所以答案为y/a+1
代码
1 #include <cstdio> 2 #include <iostream> 3 #include <algorithm> 4 #include <cmath> 5 #include <cstring> 6 #include <queue> 7 #include <vector> 8 #include <string> 9 #include <memory.h> 10 using namespace std; 11 long long a,b,c,ans; 12 long long exgcd(long long a,long long b,long long &x,long long &y) 13 { 14 if (!b) 15 { 16 x=1,y=0;return a; 17 } 18 long long e=exgcd(b,a%b,x,y),k=x; 19 x=y;y=k-a/b*y; 20 return e; 21 } 22 void doit(long long a,long long b,long long c) 23 { 24 long long x=0,y=0,d=exgcd(a,b,x,y); 25 if (c%d) 26 { 27 printf("0\n"); 28 return; 29 } 30 long long p=b/d; 31 x=((c/d%p*x)%p+p)%p,y=(c-a*x)/b; 32 ans=y>=0?y/(a/d)+1:0; 33 printf("%lld\n",ans); 34 return; 35 } 36 int main() 37 { 38 freopen("cake.in","r",stdin); 39 freopen("cake.out","w",stdout); 40 int t; cin>>t; 41 while (t--) 42 { 43 scanf("%lld%lld%lld",&a,&b,&c); 44 doit(a,b,c); 45 } 46 return 0; 47 }