CSU1209-Three Jugs-GCD

本文介绍了一个有趣的数学问题——三壶取水问题,探讨如何利用三个容量不同的壶通过倒水操作得到任意精确的水量。文章提供了使用扩展欧几里德算法来解决此问题的C++代码实现,并解释了其背后的数学原理。

Y: Three Jugs

Description

​ We have three jugs A, B, C without any calibration, and an infinite supply of water. There are three types of actions that you can use:
​ (1) Fill a jug.
​ (2) Empty a jug.
​ (3) Pour from one jug to another.
​ Pouring from one jug to another stops when the first jug is empty or the second jug is full, whichever comes first. For example, if A has 5 gallons, B has 6 gallons and a capacity of 8, then pouring from A to B leaves B full and 3 gallons in A.
​ Now you need to calculate the minimum accurate gallons of water we can get by using the three jugs.

Input

​ There is an integer T (1 <= T <= 200) in the first line, means there are T test cases in total.
​ For each test case, there are three integers a, b, c (1 <= a, b, c <= 10^18) in a line, indicate the capacity (unit: gallon) of the three jugs.

Output

​ For each test case, you should print one integer in a line, indicates the minimum accurate gallons of water we can get by using the three jugs.

Sample Input

2
3 6 9
6 10 15

Sample Output

3
1

这个题就是找三个数的gcd,用的定理如下:
扩展欧几里德算法是用来在已知a, b求解一组x,y,使它们满足贝祖等式: ax+by = gcd(a, b) =d(解一定存在,根据数论中的相关定理)。扩展欧几里德常用在求解模线性方程及方程组中。
证明过程有需要的说下我再搞

#include <bits/stdc++.h>
#define N 10100
#define INF 0x3f3f3f3f
#define LL long long
#define mem(a,n) memset(a,n,sizeof(a))
#define fread freopen("in.txt","r",stdin)
#define fwrite freopen("out.txt","w",stdout)
using namespace std;
LL gcd(LL a,LL b){
    if(a<b){
        swap(a,b);
    }
    return (b==0?a:gcd(b,a%b));
}
int main()
{
    ios::sync_with_stdio(false);
    LL a,b,c,t;
    cin>>t;
    while(t--){
        cin>>a>>b>>c;
        LL ans=gcd(a,b);
//      cout<<ans<<endl;
        ans=gcd(ans,c);
        cout<<ans<<endl;
    }
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值