题意:选出一个最大子集,其中任意两个数a、b不能满足a=素数*b。
题解:素数+二分图
最大独立子集问题。
先将所有素数存进vv,再对所有数的素数倍数建边。
建双边,建边的时候用编号,即每个数与集合中它的素数倍建双边,最后除以2即是最大匹配,再用n减去就是最大独立子集。
注意用HK,不然tle。
#define _CRT_SECURE_NO_WARNINGS
#include<iostream>
#include<cstdio>
#include<string>
#include<cstring>
#include<algorithm>
#include<queue>
#include<stack>
#include<cmath>
#include<vector>
#include<fstream>
#include<map>
#define ll long long
using namespace std;
//二分图匹配(最大独立子集)
const int maxn = 4e4 + 10;
const int Maxn = 5e5;
int n, t, a[maxn], prime[Maxn];
const int INF = 0x3f3f3f3f;
vector<int> G[maxn];
int uN; //左端顶点数
int Mx[maxn], My[maxn];
int dx[maxn], dy[maxn];
int dis;
bool used[maxn];
bool SearchP() {
queue<int>Q;
dis = INF;
memset(dx, -1, sizeof(dx));
memset(dy, -1, sizeof(dy));
for (int i = 1; i <= uN; i++)
if (Mx[i] == -1) {
Q.push(i);
dx[i] = 0;
}
while (!Q.empty()) {
int u = Q.front();
Q.pop();
if (dx[u] > dis)break;
int sz = G[u].size();
for (int i = 0; i < sz; i++) {
int v = G[u][i];
if (dy[v] == -1) {
dy[v] = dx[u] + 1;
if (My[v] == -1)dis = dy[v];
else {
dx[My[v]] = dy[v] + 1;
Q.push(My[v]);
}
}
}
}
return dis != INF;
}
bool DFS(int u) {
int sz = G[u].size();
for (int i = 0; i < sz; i++) {
int v = G[u][i];
if (!used[v] && dy[v] == dx[u] + 1) {
used[v] = true;
if (My[v] != -1 && dy[v] == dis)continue;
if (My[v] == -1 || DFS(My[v])) {
My[v] = u;
Mx[u] = v;
return true;
}
}
}
return false;
}
int MaxMatch() {
int res = 0;
memset(Mx, -1, sizeof(Mx));
memset(My, -1, sizeof(My));
while (SearchP()) {
memset(used, false, sizeof(used));
for (int i = 1; i <= uN; i++)
if (Mx[i] == -1 && DFS(i))
res++;
}
return res;
}
vector<int>vv;
map<int, int> m;
int main() {
prime[0] = 1;
prime[1] = 1;
for (int i = 2; i * i < Maxn; i++) { //0表示素数
if (!prime[i]) {
for (int j = i * 2; j < Maxn; j = j + i) {
prime[j] = 1;
}
}
}
for (int i = 2; i < Maxn; i++) { //去除1
if (!prime[i]) {
vv.push_back(i);
}
}
int len = vv.size();
scanf("%d", &t);
int cas = 1;
while (t--) {
scanf("%d", &n);
m.clear();
for (int i = 1; i <= n; i++) {
scanf("%d", &a[i]);
m[a[i]] = i;
G[i].clear();
}
for (int i = 1; i <= n; i++) {
for (int j = 0; j < len && 1ll * vv[j] * a[i] <= Maxn; j++) {
int p = m[vv[j] * a[i]];
if (p) {
G[i].push_back(p);
G[p].push_back(i);
}
}
}
uN = n;
printf("Case %d: %d\n", cas++, n - MaxMatch()/2);
}
return 0;
}