Codeforces264 B. Good Sequences

时间:2023-03-10 00:57:07
Codeforces264 B. Good Sequences

Codeforces题号:#264B

出处: Codeforces

主要算法:DP

难度:4.8

思路分析:

  这题DP太难了……

  最终的解法是,令f[i]表示存在因子i的一个数作为子序列结尾的子序列的最大长度。(定义都好难懂啊……)

  现在想一想怎么转移……首先先预处理出对于每一个数a[i]的所有因数(不含1)。既然相邻的两个数不能是互质的,我们只需要判断相邻两个数的最大公约数是否大于1就好了。

  依次枚举a[i],在这过程中枚举刚才处理好的a[i]的因数。为什么要枚举因数? 为了看看我能够接到哪些数后面。因为所有因数如果在之前的数里出现过,那么当前的a[i]就可以接上去,因为因数大于1,所以肯定不会有互质的这种情况。由于我之前已经记录了这些因数所能够达到的最大长度,那么再加上我自己,长度就又可以+1了——这一点有点像LIS,但又有点不同:选择所有因数中f值最大的去接上去以后,所有因数的f值都可以更新成与其中最大值相同的。因为最后一个数本身就含有这些因数。

  所以最后的答案究竟是什么?我认为是f[2]~f[a[n]中的最大值。然而这样会WA,改成f[1]~f[a[n]]就AC了。这一点一直想不通,是因为本身就会输入1吗?为什么输入1就会影响答案呢?而且我的AC代码对于数据1 1 1 1 1竟然输出了5,不应该是1吗?1和1是互质的!还请大神帮忙解答一下……

代码注意点:

  无

Code

/** This Program is written by QiXingZhi **/
#include <cstdio>
#include <queue>
#include <cstring>
#include <algorithm>
#include <cmath>
#define r read()
#define Max(a,b) (((a)>(b)) ? (a) : (b))
#define Min(a,b) (((a)<(b)) ? (a) : (b))
using namespace std;
typedef long long ll;
const int N = ;
const int INF = ;
inline int read(){
int x = ; int w = ; register int c = getchar();
while(c ^ '-' && (c < '' || c > '')) c = getchar();
if(c == '-') w = -, c = getchar();
while(c >= '' && c <= '') x = (x << ) +(x << ) + c - '', c = getchar();
return x * w;
}
int n,cur,_max,ans;
int a[N],f[N];
vector <int> factor[N];
inline void MadeFactor(int I){
int x = a[I];
int lim = floor(sqrt(x));
factor[I].push_back(x);
for(int i = ; i <= lim; ++i){
if(x % i == ){
factor[I].push_back(i);
if(i!=x/i) factor[I].push_back(x/i);
}
}
}
int main(){
// freopen(".in","r",stdin);
n = r;
for(int i = ; i <= n; ++i){
a[i] = r;
MadeFactor(i);
   }
for(int i = ; i <= n; ++i){
_max = ;
int sz = factor[i].size();
for(int j = ; j < sz; ++j){
cur = factor[i][j];
++f[cur];
_max = Max(_max, f[cur]);
}
for(int j = ; j < sz; ++j){
f[factor[i][j]] = _max;
}
}
for(int i = ; i <= a[n]; ++i){
ans = Max(ans, f[i]);
}
printf("%d",ans);
return ;
}