Strange Beauty
Polycarp found on the street an array 𝑎 of 𝑛 elements.Polycarp invented his criterion for the beauty of an array. He calls an array 𝑎 beautiful if at least one of the following conditions must be met for each different pair of indices 𝑖≠𝑗: 𝑎𝑖 is divisible by 𝑎𝑗 or 𝑎𝑗 is divisible by 𝑎𝑖.
For example, if:
𝑛=5 and 𝑎=[7,9,3,14,63], then the 𝑎 array is not beautiful (for 𝑖=4 and 𝑗=2, none of the conditions above is met);
𝑛=3 and 𝑎=[2,14,42], then the 𝑎 array is beautiful;
𝑛=4 and 𝑎=[45,9,3,18], then the 𝑎 array is not beautiful (for 𝑖=1 and 𝑗=4 none of the conditions above is met);
Ugly arrays upset Polycarp, so he wants to remove some elements from the array 𝑎 so that it becomes beautiful. Help Polycarp determine the smallest number of elements to remove to make the array 𝑎 beautiful.
Input
The first line contains one integer 𝑡 (1≤𝑡≤10) — the number of test cases. Then 𝑡 test cases follow.
The first line of each test case contains one integer 𝑛 (1≤𝑛≤2⋅10^5) — the length of the array 𝑎.
The second line of each test case contains 𝑛 numbers 𝑎1,𝑎2,…,𝑎𝑛 (1≤𝑎𝑖≤2⋅10^5) — elements of the array 𝑎.
Output
For each test case output one integer — the minimum number of elements that must be removed to make the array 𝑎 beautiful.
Example
input:
4
5
7 9 3 14 63
3
2 14 42
4
45 9 3 18
3
2 2 8
output:
2
0
1
0
这是Div3的最后一题,也不难,不知道为什么就是没想到。题目的意思很简单,如果数组中任意两个数都存在整除关系(即对于任意 a i a_i ai a j a_j aj,都满足 a i ∣ a j a_i | a_j ai∣aj或者 a j ∣ a i a_j | a_i aj∣ai),那么这个数组就是美的。现在给一个数组,问最少移除几个元素能使数组变成美的?
一个美的数组我们也知道,所有元素从小到大排序的话,依次都会存在整除关系。我想的是去对所有数的整除关系建个图,然后找到图里面的最长链就是答案了,但没想到如何在 O ( n l o g n ) O(nlogn) O(nlogn)时间内把图建出来。其实这道题这个方法应该不行,第一,要注意到数组里可以有重复元素,所以图是有自环的,而这又无法简单表示出有几个重复元素。第二,对于一个所有元素都存在整除关系的数组,所有点之间都要连边,那边的数量就可以达到亿级。
其实这道题用dp可以轻松解决,我也不知道为什么我没想到dp。。怎么想到dp呢,首先排序不影响结果,做个计数。其实刚才第一种思路,我们就是想找最长的整除链。对于某个元素
a
i
a_i
ai结尾的链,所有和
a
i
a_i
ai重复的值肯定都包括在内,那比
a
i
a_i
ai小的呢?可以穷举比
a
i
a_i
ai小并且可以被整除的
a
j
a_j
aj,那么有如下公式(i和j指的是值):
d
p
[
i
]
=
m
a
x
j
∣
i
{
d
p
[
j
]
+
c
n
t
[
i
]
}
dp[i] = max_{j | i}\{dp[j] + cnt[i]\}
dp[i]=maxj∣i{dp[j]+cnt[i]}
那么怎么穷举i的所有因子?直接穷举不太方便的话,那我们就逆向的做,每次计算dp[i]的时候,用筛法去更新2i, 3i…
//
// main.cpp
//
//
// Created by ji luyang on 2020/12/22.
//
#include <stdio.h>
#include <iostream>
#include <fstream>
#include <string>
#include <cstring>
#include <time.h>
#include <algorithm>
#include <vector>
#include <queue>
#include <map>
using namespace std;
int t;
int n;
int cnt[200010], dp[200010];
int main() {
ios_base::sync_with_stdio(0); cin.tie(0);
cin >> t;
while (t--) {
memset(cnt, 0, sizeof(cnt));
cin >> n;
for (int i = 1; i <= n; i++) {
int x;
cin >> x;
cnt[x]++;
}
for (int i = 1; i <= 200000; i++) {
dp[i] = cnt[i];
}
int maxl = 0;
for (int i = 1; i <= 200000; i++) {
for (int j = 2 * i; j <= 200000; j += i) {
dp[j] = max(dp[j], cnt[j] + dp[i]);
}
maxl = max(maxl, dp[i]);
}
cout << n - maxl << endl;
}
return 0;
}