本题出自杭电多校第一场
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]);
}
}
该博客讨论了如何利用欧拉筛预处理合数和质数的前缀和,来快速求解给定节点数量的最小生成树问题。题目中提到,对于每个编号为3到n的点,如果它是合数则连接其约数,如果是质数则连接到2,以此构造最小生成树。算法的时间复杂度为O(n),并给出了相应的C++代码实现。
584

被折叠的 条评论
为什么被折叠?



