F - Minimum Sum of Array(素数筛)
You are given an array a consisting of n integers a1, ..., an. In one operation, you can choose 2 elements ai and aj in which ai is divisible by aj and transform ai to aj.
A number x is said to be divisible by a number y if x can be divided by y and the result is an exact whole number. For example, 15 is divisible by 3, because 15÷ 3 = 5 exactly, but 9 is not divisible by 2 because 9÷ 2 is 4 with 1 left over.
Your task is to find the minimum sum of the array a that can be obtained by making as many transform operations as you want. Can you?
Input
The first line contains an integer T (1 ≤ T ≤ 100) specifying the number of test cases.
The first line of each test case contains an integer n (1 ≤ n ≤ 105), in which n is the size of array a. Then a line follows containing n integers a1, ..., an (1 ≤ ai ≤ 106), giving array a.
The sum of n overall test cases does not exceed 3 × 106.
Output
For each test case, print a single line containing the minimum sum of the array athat can be obtained after making as many transform operations as you want.
Example
Input
1 5 2 2 3 6 6
Output
11
题意:给出n个数,当一个数可以被另一个数整除时,大的变成小的。 12 3 -> 12/3 = 4,所以12变成3
思路:用via[i]=1 表示i这个数字出现了一次。素数筛1~maxx,如果via[i]>0 则筛i的倍数。
代码:
#include <bits/stdc++.h>
using namespace std;
const int maxn = 1e6;
int via[maxn];
int main()
{
int listt;
long long n,i,x,j;
scanf("%d",&listt);
while ( listt-- ) {
memset(via,0,sizeof(via));
long long maxx = 0;
scanf("%lld",&n);
for ( i=0; i<n; i++ ) {
scanf("%lld",&x);
maxx = max(maxx,x);
via[x] ++;
}
for ( i=1; i<=maxx; i++ ) {
if ( via[i]>0 ) {
for ( j=2; i*j<=maxx; j++ ) {
if ( via[i*j]>0 ) {
via[i] += via[i*j];
via[i*j] = 0;
}
}
}
}
long long ans = 0;
for ( i=1; i<=maxn; i++ ) {
if ( via[i]>0 ) {
ans += via[i]*i;
}
}
printf("%lld\n",ans);
}
return 0;
}