【Codeforces 264B】Good Sequences

【链接】 我是链接,点我呀:)
【题意】


让你在一个递增数组中选择一个最长子序列使得gcd(a[i],a[i+1])>1

【题解】


设f[i]表示以一个"含有素因子i的数字"作为序列的结尾的最长序列的长度
显然更新的时候
假设枚举到了a[i]
先求出它所有的素因子p[]
因为要和前面一个数字不互质
那么只能找结尾数字有这些素因子p[]的数字
因此我们求出f[p[1~cnt]]中的最大值Ma,他们最大值对应的序列再加上一个a[i]的话
长度就变成Ma+1了
然后f[p[1~cnt]]就能用Ma+1的值来尝试更新了
因为a[i]含有这些因子
注意只有一个数字1的情况,这种时候只选一个1是不和任何数字互质的,也是满足条件的。
抓住不互质就是有共同素因子这一点很重要。

【代码】

import java.io.*;
import java.util.*;

public class Main {
    
    
    static InputReader in;
    static PrintWriter out;
        
    public static void main(String[] args) throws IOException{
        //InputStream ins = new FileInputStream("E:\\rush.txt");
        InputStream ins = System.in;
        in = new InputReader(ins);
        out = new PrintWriter(System.out);
        //code start from here
        new Task().solve(in, out);
        out.close();
    }
    
    static int N = (int)1e5;
    static class Task{
        int n;
        int a[] = new int[N+10];
        int f[] = new int[N+10];
        int p[] = new int[N+10];
        
        public void solve(InputReader in,PrintWriter out) {
            n = in.nextInt();
            for (int i = 1;i <= n;i++) a[i] = in.nextInt();
            int ans = 0;
            for (int i = 1;i <= n;i++) {
                int cnt = 0;
                int x = a[i];
                for (int j = 2;j*j<=x;j++) {
                    if (x%j==0){
                        p[++cnt] = j;
                        while (x%j==0) {
                            x/=j;
                        }
                    }
                }
                if (x>1) p[++cnt] = x;
                int ma = 0;
                for (int j = 1;j <= cnt;j++) 
                    ma = Math.max(ma, f[p[j]]+1);
                if (a[i]==1) ma = 1;
                ans = Math.max(ma, ans);
                for (int j = 1;j <= cnt;j++)
                    f[p[j]] = Math.max(f[p[j]], ma);
            }
            out.println(ans);
        }
    }

    

    static class InputReader{
        public BufferedReader br;
        public StringTokenizer tokenizer;
        
        public InputReader(InputStream ins) {
            br = new BufferedReader(new InputStreamReader(ins));
            tokenizer = null;
        }
        
        public String next(){
            while (tokenizer==null || !tokenizer.hasMoreTokens()) {
                try {
                tokenizer = new StringTokenizer(br.readLine());
                }catch(IOException e) {
                    throw new RuntimeException(e);
                }
            }
            return tokenizer.nextToken();
        }
        
        public int nextInt() {
            return Integer.parseInt(next());
        }
    }
}

猜你喜欢

转载自www.cnblogs.com/AWCXV/p/10503044.html
今日推荐