AtCoder---Multiple Clocks(多个时钟)(n个数的最小公倍数公式应用)

题目描述

We have N clocks. The hand of the i-th clock (1≤i≤N) rotates through 360° in exactly Ti seconds.
Initially, the hand of every clock stands still, pointing directly upward.
Now, Dolphin starts all the clocks simultaneously.
In how many seconds will the hand of every clock point directly upward again?

译文:我们这有N个钟表。第i个钟表的指针旋转一周要正正好好Ti秒。一开始,这些表的指针静止不动,指向为竖直向上。现在,dolphin(海豚)先生同时启动了所有钟表。在多少秒后所有钟表的指针会再次指向竖直向上?
Constraints
1≤N≤100
1≤Ti≤1e18
All input values are integers.

译文:所有输入皆为整数
The correct answer is at most 1e18 seconds.

译文:正确答案不会超过long long(1e18)范围

输入

Input is given from Standard Input in the following format:
N
T1
:  
TN

输出

Print the number of seconds after which the hand of every clock point directly upward again.

样例输入

复制样例数据

2
2
3

样例输出

6

提示

We have two clocks. The time when the hand of each clock points upward is as follows:
·Clock 1: 2, 4, 6, … seconds after the beginning
·Clock 2: 3, 6, 9, … seconds after the beginning
Therefore, it takes 6 seconds until the hands of both clocks point directly upward.

根据题面,这个题的答案很明显为n个数的最小公倍数,因为只有“公倍数”秒后才会有“公共的”状态即同时指向竖直向上。问题是我们都知道两个数的最小公倍数(LCM)为a*b/(a,b)((a,b)为a,b最大公因数),那么怎么解决n个数的最小公倍数问题呢?

我们可以用类似动态规划的思想(形式类似但是这里没有用到真正的动态规划),把一个大问题分解成多个子问题,然后逐一解决,很明显这里可分解的最小子问题为“两个数的的最小公倍数”,这些问题的公共解就是n个数的最小公倍数。

也就是说,对于每两个数,我们要求出它的最小公倍数,然后用这个最小公倍数代表这之前的数(这个数一定是前面数的倍数,它和下一个元素的最小公倍数也是前面数的倍数)与后面的数继续计算最小公倍数。

#include <iostream>
#include <cstdio>
#include <bits/stdc++.h>
#include <iomanip>
#include <cstring>
#include <cmath>
#define DETERMINATION main
#define lldin(a) scanf("%lld",&a)
#define din(a) scanf("%d",&a)
#define reset(a,b) memset(a,b,sizeof(a))
const int INF=0x3f3f3f3f;
using namespace std;
typedef long long ll;
typedef long double ld;
/**Although there will be many obstructs ahead of you,
the desire for victory still fills you with determination..**/
ll a[5000];
bool cmp(ll a,ll b)
{
    return a>b;
}
template<typename T>//C++的模板类型,就是一个通用板子……体现了OOP的好处。
T gcd(T a,T b)//最大公约数
{
    return b==0?a:gcd(b,a%b);
}
template<typename T>
T lcm(T a,T b)//最小公倍数
{
    ll g=gcd(a,b);
    return (a/g)*b;
}
int DETERMINATION()
{
    ll n;
    cin>>n;
    for(int i=1;i<=n;i++)
        cin>>a[i];
    ll ans=1;//指派为1即可,或者直接拿最大元素初始化也行。
    for(int i=1;i<=n;i++)
    {
        ans=lcm(ans,a[i]);
    }
    cout<<ans<<endl;
    return 0;
}

猜你喜欢

转载自blog.csdn.net/weixin_43874261/article/details/88881009