Minimum spanning tree

该博客讨论了如何利用欧拉筛预处理合数和质数的前缀和,来快速求解给定节点数量的最小生成树问题。题目中提到,对于每个编号为3到n的点,如果它是合数则连接其约数,如果是质数则连接到2,以此构造最小生成树。算法的时间复杂度为O(n),并给出了相应的C++代码实现。
摘要由CSDN通过智能技术生成

本题出自杭电多校第一场

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]);
	}	
}
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值