题解1475G Strange Beauty( 动态规划DP+因子数论筛)

题解1475G Strange Beauty[DP+因子数论筛]

题目

Description:
Polycarp found on the street an array a of n elements.

Polycarp invented his criterion for the beauty of an array. He calls an array a beautiful if at least one of the following conditions must be met for each different pair of indices i≠j:

ai is divisible by aj;
or aj is divisible by ai.
For example, if:

n=5 and a=[7,9,3,14,63], then the a array is not beautiful (for i=4 and j=2, none of the conditions above is met);
n=3 and a=[2,14,42], then the a array is beautiful;
n=4 and a=[45,9,3,18], then the a array is not beautiful (for i=1 and j=4 none of the conditions above is met);
Ugly arrays upset Polycarp, so he wants to remove some elements from the array a so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array a beautiful.

Input:
The first line contains one integer t (1≤t≤10) — the number of test cases. Then t test cases follow.

The first line of each test case contains one integer n (1≤n≤2⋅105) — the length of the array a.

The second line of each test case contains n numbers a1,a2,…,an (1≤ai≤2⋅105) — elements of the array a.

e.g.
4
5
7 9 3 14 63
3
2 14 42
4
45 9 3 18
3
2 2 8

Output:
For each test case output one integer — the minimum number of elements that must be removed to make the array a beautiful.

e.g.
2
0
1
0

解析

  • TAG:
    DP+数论筛

  • DESCRIPITION:
    找整数集合的最大可比子集,其中任意两个元素都"可比"(即beauty),"可比"指一个数是另一个数的因子。

  • INPUT:
    t组数据(1≤t≤10) ,整数集合a大小为n(1≤n≤2e5) ,其中有整数a1~an(1≤ai≤2e5)

  • SOLUTION:

  1. dp数组:dp[i]=以整数i为最大值的最大子集大小
  2. cnt数组:cnt[i]=整数i在集合内的数量
  3. dp递推式:dp[x]=cnt[x]+dp[y] (y|x,1<=y<x),用筛法考虑一个数是哪些数的真因子,即可自小向大筛快速求出dp
  4. (1)先根据输入对每一个出现过的整数计数,放在cnt数组内;
    (2)x从1到MAXN遍历cnt数组,dp[x]既然是以x为最大数的可比子集数量,当然要加上cnt[x],dp[x] += cnt[x];
    (3)然后用这个x去自小到大去筛x的倍数的dp值,这时候要用到dp递推公式dp[k] = max(dp[k], dp[x]);
    (4)最后找到最大的dp值。

参考源码

#include<iostream>
#include<algorithm>
#include<cstring>
using namespace std;

const int NMAX = 2e5 + 10;
int cnt[NMAX];
int dp[NMAX];

int main() {
	int t, n, a;
	ios::sync_with_stdio(false);
	cin >> t;
	while (t--) {
		cin >> n;
		memset(cnt, 0, sizeof(cnt));
		memset(dp, 0, sizeof(cnt));
		for (int i = 0; i < n; i++) {
			cin >> a;
			cnt[a]++;
		}
		for (int x = 1; x < NMAX; x++) {
			dp[x] += cnt[x];
			//因子筛
			for (int k = x * 2; k < NMAX; k += x)
				//if (cnt[k] && cnt[x])加不加都可以
				//因为该筛法是在令倍数的dp值=当前max值,最后求得就是整个dp数组中的max值,具体哪个是最大无所谓
				dp[k] = max(dp[k], dp[x]);
		}
		cout << n - *max_element(dp, dp + NMAX) << endl;//STL求dp数组中的max值
	}
	return 0;
}



  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值