CodeForces_Minimum Sum of Array(思路)

本文探讨了一道算法题目,要求通过将数组中可整除的元素进行转换,以达到数组最小和的目标。介绍了问题背景,给出了具体的操作规则,并通过代码示例展示了如何解决这一问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目链接: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.

题目大意:一组数,有这种操作:如果a能被b整除,可以把a变成b,求不限制次数操作后的数组最小和。

思路:看代码即可。

#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
const int maxn=1000010;
using namespace std;
 
int cnt[1000010];//用来存i一共有几个 
int main(){
	std::ios::sync_with_stdio(false);
	int t;
	cin>>t;
	while(t--)
	{
		ll n,x,sum=0,maxn=0;
		cin>>n;
		for(ll i=0; i<=1000000;i++) cnt[i]=0;//别忘了每次清0 
		for(ll i=1;i<=n;i++)
		{
			cin>>x;
			cnt[x]++;
			maxn=max(x,maxn);
		}
		for(int i=1;i<=maxn;i++)
		{
			if(cnt[i]>0)
			{
				for(ll j=2;i*j<=maxn;j++)
				{
					if(cnt[i*j]>0)
					{
						cnt[i]+=cnt[i*j];//大数变小数,i*j变成了i 
						cnt[i*j]=0;//大数消失 
					}
				}
			}
		}
		for(ll i=1;i<=maxn;i++)	sum+=cnt[i]*i;
		cout<<sum<<endl;
	}
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

我爱吃狮子头

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值