本题出自杭电多校第一场
Problem Description
Given n-1 points, numbered from 2 to n, the edge weight between the
two points a and b is lcm(a, b). Please find the minimum spanning tree
formed by them.A minimum spanning tree is a subset of the edges of a connected,
edge-weighted undirected graph that connects all the vertices
together, without any cycles and with the minimum possible total edge
weight. That is, it is a spanning tree whose sum of edge weights is as
small as possible.lcm(a, b) is the smallest positive integer that is divisible by both a
and b.
Input
The first line contains a single integer t (t<=100) representing the number of test cases in the input. Then t test cases
follow.The only line of each test case contains one integers n
(2<=n<=10000000) as mentioned above.
Output
For each test case, print one integer in one line, which is the minimum spanning tree edge weight sum.
对于编号为3~n的点,将所有编号为合数的点向其约数连边,编号为质数的点向2连边,不难证明这样形成的生成树是最小的。
总的边权和为(质数的和*2+合数的和),用欧拉筛预处理前缀和即可。
效率:O(n)
#include<bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef pair<int,int>pii;
const int inf=1e9;
const int N=1e6+10;
const int M=1e7+20;
const int mo=998244353;
bool v[M];
int tot,p[N],i;
ll a[N];
int n;
int main(){
int t;
for(int i=2;i<M;i++)
{
if(!v[i]){
p[++tot]=i;
}
for(int j=1;j<=tot;j++)
{
if(i*p[j]>=M)
break;
v[i*p[j]]=1;
if(!(i%p[j]))
break;
}
}
for(int i=2;i<=tot;i++){
a[i]=p[i]+a[i-1];
}
cin>>t;
while(t--){
cin>>n;
printf("%lld\n",ll(3+n)*(n-2)/2+a[upper_bound(p+1,p+tot+1,n)-p-1]);
}
}