4981: Collatz Conjecture
时间限制: 6 Sec 内存限制: 128 MB提交: 213 解决: 23
[提交][状态][讨论版][命题人:admin]
题目描述
In 1978 AD the great Sir Isaac Newton, whilst proving that P is a strict superset of N P, defined the Beta Alpha Pi Zeta function f as follows over any sequence of positive integers a1,..., an. Given integers 1 ≤ i ≤ j ≤ n, we define f(i, j) as gcd(ai, ai+1,..., aj−1, aj).
About a century later Lothar Collatz applied this function to the sequence 1, 1, 1,..., 1, and observed that f always equalled 1. Based on this, he conjectured that f is always a constant function, no matter what the sequence ai is. This conjecture, now widely known as the Collatz Conjecture, is one of the major open problems in botanical studies. (The Strong Collatz Conjecture claims that however many values f takes on, the real part is always 1/2 .)
You, a budding young cultural anthropologist, have decided to disprove this conjecture. Given a sequence ai, calculate how many different values f takes on.
About a century later Lothar Collatz applied this function to the sequence 1, 1, 1,..., 1, and observed that f always equalled 1. Based on this, he conjectured that f is always a constant function, no matter what the sequence ai is. This conjecture, now widely known as the Collatz Conjecture, is one of the major open problems in botanical studies. (The Strong Collatz Conjecture claims that however many values f takes on, the real part is always 1/2 .)
You, a budding young cultural anthropologist, have decided to disprove this conjecture. Given a sequence ai, calculate how many different values f takes on.
输入
The input consists of two lines.
• A single integer 1 ≤ n ≤ 5 · 105, the length of the sequence.
• The sequence a1, a2, . . . , an. It is given that 1 ≤ ai ≤ 1018.
• A single integer 1 ≤ n ≤ 5 · 105, the length of the sequence.
• The sequence a1, a2, . . . , an. It is given that 1 ≤ ai ≤ 1018.
输出
Output a single line containing a single integer, the number of distinct values f takes on over the given sequence.
样例输入
4
9 6 2 4
样例输出
6
记录,更新以每个元素结尾的gcd,代码很好理解!
AC代码:
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
const int MAXN=1e6;
ll gcd(ll a,ll b)
{
return b==0?a:gcd(b,a%b);
}
ll a[MAXN],g[MAXN],ans[10*MAXN];
int main()
{
ll n;
cin>>n;
for(int i=0; i<n; i++)
{
cin>>a[i];
}
ll tot=0;
ll cot=0;
for(int i=0; i<n; i++)
{
for(int j=0; j<tot; j++)
{
ll x=gcd(a[i],g[j]);
if(x!=g[j])
{
ans[cot++]=g[j];
g[j]=x;
}
}
g[tot++]=a[i];
tot=unique(g,g+tot)-g;
}
for(int i=0; i<tot; i++)
{
ans[cot++]=g[i];
}
sort(ans,ans+cot);
ll ret=unique(ans,ans+cot)-ans;
cout<<ret<<endl;
return 0;
}