4981: Collatz Conjecture
题目描述
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
枚举右端点,找出以i结尾之前所有不同的gcd,ans记录出现过的不同的gcd。
temp是递增的可以直接用unique。
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
ll gcd(ll a,ll b){
return b==0?a:gcd(b,a%b);
}
ll ans[7000005],temp[500005],x;
int main()
{
int n,m=0,k=0;
scanf("%d",&n);
for(int i=0;i<n;i++){
scanf("%lld",&x);
for(int j=0;j<m;j++){
ll t=gcd(temp[j],x);
if(t!=temp[j]){
ans[k++]=temp[j];
temp[j]=t;
}
}
temp[m++]=x;
m=unique(temp,temp+m)-temp;
}
for(int i=0;i<m;i++)
ans[k++]=temp[i];
sort(ans,ans+k);
int sum=1;
for(int i=1;i<k;i++)
if(ans[i]!=ans[i-1])
sum++;
printf("%d\n",sum);
return 0;
}