[exgcd] Jzoj P5855 吃蛋糕

Description

Beny 想要用蛋糕填饱肚子。Beny 一共想吃体积为 c 的蛋糕,他发现有两种蛋糕可以吃,一种体积为 a,一种体积为 b,但两种蛋糕各有特色。Beny 想知道他一共有多少种不同吃法, 使得他恰好可以填饱肚子。
 
 

Input

第一行一个 t
接下来 t 行,每行三个正整数 a,b,c
 

Output

对于每个 a,b,c,输出一个整数表示有几种不同吃法
 
 

Sample Input

样例输入 1
3
2 3 4
3 4 24
3 7 11
 
样例输入 2
4
12 13 1003
56 44 792
4616 5364 836482148
3836501 7035978 77151863500136
 

Sample Output

样例输出 1
13
0
 
样例输出 2
6
2
135
3
 
 

Data Constraint

对于 30%的数据 t<=10,a,b,c<=100
对于 60%的数据 t<=100,a,b,c<=10^9
对于 100%的数据 t<=10000,a,b,c<=10^14

题解

  • 其实就是求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 }

猜你喜欢

转载自www.cnblogs.com/Comfortable/p/9649074.html