JZOJ5855. 【NOIP提高组模拟A组2018.9.8】吃蛋糕

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
1
3
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的非负整数解的个数,
设d=(a,b),a’=a/d,b’=b/d,c’=c/d
如果c不能被d整除,那么就是无解。
现在先求出a’x+b’y=1的一组解 ( x 0 , y 0 ) 来,
用扩展欧几里得解决。
然后 ( x 0 c , y 0 c ) 就是a’x+b’y=c’的一组解,
然后就可以统计非负整数解了。

code

#include <queue>
#include <cstdio>
#include <iostream>
#include <algorithm>
#include <cstring>
#include <string.h>
#include <cmath>
#define ll long long
#define N 100003
#define M 103
#define P putchar
#define G getchar
using namespace std;
char ch;
void read(ll &n)
{
    n=0;
    ch=G();
    while((ch<'0' || ch>'9') && ch!='-')ch=G();
    ll w=1;
    if(ch=='-')w=-1,ch=G();
    while('0'<=ch && ch<='9')n=(n<<3)+(n<<1)+ch-'0',ch=G();
    n*=w;
}

int max(int a,int b){return a>b?a:b;}
int min(int a,int b){return a<b?a:b;}
void write(ll x){if(x>9) write(x/10);P(x%10+'0');}

ll gcd(ll x,ll y){return ((x%y)?gcd(y,x%y):y);}

ll exgcd(ll a,ll b,ll& x,ll& y)
{
    if(b==0)
    {
        x=1;y=0;return a;
    }
    else
    {
        ll d=exgcd(b,a%b,y,x);
        y=y-a/b*x;
        return d;
    }
}

ll T,a,b,c,d,x,y;

int main()
{
    freopen("cake.in","r",stdin);
    freopen("cake.out","w",stdout);

    for(read(T);T;T--)
    {
        read(a);read(b);read(c);
        if(a<b)swap(a,b);
        d=gcd(a,b);
        if(c%d)
        {
            P('0'),P('\n');
            continue;
        }
        a=a/d;b=b/d;c=c/d;
        exgcd(a,b,x,y);
        x=(x%b+b)%b;
        x=x*(c%b);
        x=(x%b+b)%b;
        y=(c-a*x)/b;
        if(y<0)P('0');else write(y/a+1);P('\n');
    }

    return 0;
}

猜你喜欢

转载自blog.csdn.net/lijf2001/article/details/82532792