7.20 第一场 Minimum spanning tree
Minimum spanning tree
Time Limit: 2000/1000 MS (Java/Others) Memory Limit: 524288/524288 K (Java/Others)
Total Submission(s): 81 Accepted Submission(s): 43
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.
Sample Input
2
2
6
Sample Output
0
26
大概题意
求n个节点的最小生成树,两两节点之间边的权值为两数的最小公倍数。
思路
惯性思维考虑了克鲁斯卡尔的复杂度。。。。。发现这数据量有点费劲
冷静过后梳理样例发现规律
若定点为素数,则与2相连时权值最小
若定点不为素数,则与其因数相连时权值最小
据此编写代码
代码
#include<iostream>
#include<cstdio>
using namespace std;
const int N = 10000010;
int primes[N], cnt; // primes[]存储所有素数
bool st[N]; // st[x]存储x是否被筛掉
void get_primes(int n) {
for (int i = 2; i <= n; i++) {
if (!st[i]) primes[cnt++] = i;
for (int j = 0; primes[j] <= n / i; j++) {
st[primes[j] * i] = true;
if (i % primes[j] == 0) break;
}
}
}
int main() {
int t;
long long n;
cin >> t;
get_primes(10000010);
while (t--) {
cin >> n;
long long res = 0;
for (int i = 3; i <= n; ++i) {
if (!st[i])res += i * 2;
else res += i;
}
cout << res << endl;
}
return 0;
}
//6 4 10 6
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库
· SQL Server 2025 AI相关能力初探
· 为什么 退出登录 或 修改密码 无法使 token 失效