北邮校赛 I. Beautiful Array(DP)

本文介绍了一个算法问题BeautifulArray,目标是最小化删除数组中的元素,使剩余元素的每一对相邻数的最大公约数大于等于给定阈值。文章提供了一种通过动态规划和因子更新的方法来解决该问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

时间限制 1000 ms 内存限制 65536 KB

题目描述

We call an array "beautiful array of level L", when all its adjacent number pairs have common factor greater than or equal to L. Obviously, a "beautiful array of level L" is also a "beautiful array of level L1", and so on. Now you are required to remove some elements from a given array of length n, in order to make it become "beautiful array of level L". Try to figure out the maximum length of the new array.

输入格式

The first line contains only one integer T(1T5), which indicates the number of test cases.
For each test case:

  • The first line contains two integers n,L(1n50000,2L1000000);
  • The second line contains n integers a1,a2,...,an(2ai1000000).

 

输出格式

For each test case, output a number in a single line, indicating the maximum number of elements retained in the array.

输入样例

1
5 6
7 16 9 24 6

输出样例

3
【题意】给你一个数组,然你删除尽量少的数,使得剩下的数,相邻的两个数的GCD>=K,数的相对位置不变,问你剩下的数最多有几个。
【分析】我们可以从左往右遍历,对于每个数,我们更新一下它的所有因子最近出现的位置。然后对于当前数,我们找到它的所有因子
然后查找这个因子最近出现的位置,然后从那个地方DP过来,然后更新这个因子的位置。
#include <bits/stdc++.h>
#define mp make_pair
#define pb push_back
#define met(a,b) memset(a,b,sizeof a)
#define inf 10000000
using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
const int N = 1e6+5;
const double eps = 1e-8;
int n,sum[N],m,cnt,k;
int lazy[N],a[N];
int p[N],dp[N];
void solve(int x){
    for(int i=2;i*i<=a[x];i++){
        if(a[x]%i==0){
            if(i>=m&&p[i]!=0)dp[x]=max(dp[x],dp[p[i]]+1);
            if(a[x]/i>=m&&p[a[x]/i]!=0)dp[x]=max(dp[x],dp[p[a[x]/i]]+1);
            p[i]=x;
            p[a[x]/i]=x;
        }
    }
    if(p[a[x]]!=0&&a[x]>=m)dp[x]=max(dp[x],dp[p[a[x]]]+1);
    p[a[x]]=x;
}
int main() {
    int T,x,y,xx,yy;
    scanf("%d",&T);
    while(T--){
        scanf("%d%d",&n,&m);
        met(p,0);
        bool ok=false;
        for(int i=1;i<=n;i++){
            scanf("%d",&a[i]);
            if(a[i]>=m)ok=true;
            dp[i]=0;
        }
        for(int i=1;i<=n;i++){
            if(a[i]<m)continue;
            else dp[i]=1;
            solve(i);
        }
        int ans=0;
        for(int i=1;i<=n;i++){
            ans=max(ans,dp[i]);
        }
        printf("%d\n",ans);
    }
    return 0;
}

 

转载于:https://www.cnblogs.com/jianrenfang/p/6789029.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值