题解 | #kotori和素因子#
kotori和素因子
https://www.nowcoder.com/practice/7b1c858a3e7a41ed8364178979eaae67
#include <iostream>
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 1e3 + 5;
const int INF = 0x3f3f3f3f;
vector <int> e[maxn];
int m, n, x,sum,minS;
bool vis[maxn], flag;
bool fun(int k) {// 是否为素数
if (k == 1) return false;
for (int i = 2; i <= floor(sqrt(k)); i++) {
if (k % i == 0)
return false;
}
return true;
}
void prime(int k,int x) {//存数
for (int i = 1; i <= floor(sqrt(k)); i++) {
if (k % i == 0) {
if (fun(i))
e[x].push_back(i);
if (i * i != k && fun(k / i))
e[x].push_back(k / i);
}
}
}
void dfs(int y) {
if (y == x) {
minS = min(minS, sum);
flag = 1;
return;
}
for (int i = 0; i < e[y].size(); i++) {
if (!vis[e[y][i]]) {
sum += e[y][i];
vis[e[y][i]] = 1;
dfs(y + 1);
sum -= e[y][i];
vis[e[y][i]] = 0;
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> m;
prime(m,x++);
}
minS = INF;
dfs(0);
if (flag == 1) {
cout << minS;
}
else
cout << -1;
return 0;
}
#include <algorithm>
#include <cmath>
#include <vector>
using namespace std;
const int maxn = 1e3 + 5;
const int INF = 0x3f3f3f3f;
vector <int> e[maxn];
int m, n, x,sum,minS;
bool vis[maxn], flag;
bool fun(int k) {// 是否为素数
if (k == 1) return false;
for (int i = 2; i <= floor(sqrt(k)); i++) {
if (k % i == 0)
return false;
}
return true;
}
void prime(int k,int x) {//存数
for (int i = 1; i <= floor(sqrt(k)); i++) {
if (k % i == 0) {
if (fun(i))
e[x].push_back(i);
if (i * i != k && fun(k / i))
e[x].push_back(k / i);
}
}
}
void dfs(int y) {
if (y == x) {
minS = min(minS, sum);
flag = 1;
return;
}
for (int i = 0; i < e[y].size(); i++) {
if (!vis[e[y][i]]) {
sum += e[y][i];
vis[e[y][i]] = 1;
dfs(y + 1);
sum -= e[y][i];
vis[e[y][i]] = 0;
}
}
}
int main() {
cin >> n;
for (int i = 0; i < n; i++) {
cin >> m;
prime(m,x++);
}
minS = INF;
dfs(0);
if (flag == 1) {
cout << minS;
}
else
cout << -1;
return 0;
}