2021“MINIEYE杯”中國大學生演算法設計超級聯賽(1)1005. Minimum spanning tree(min25篩)
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
手玩樣例很容易就能發現所有合數一定和質因子相連,所以邊權為本身,質數一定和2相連,因此邊權是這個質數 * 2。所以總的答案就是2到n求和再加上n以內的質數和再減去2 * 2。n以內的質數和可以用min25篩求。
#include <bits/stdc++.h> #define int long long using namespace std; typedef long long ll; const int N = 1000010; struct Min25 { ll prime[N], id1[N], id2[N], flag[N], ncnt, m; ll g[N], sum[N], a[N], T, n; inline int ID(ll x) { return x <= T ? id1[x] : id2[n / x]; } inline ll calc(ll x) { return x * (x + 1) / 2 - 1; } inline ll f(ll x) { return x; } inline void Init() { memset(prime, 0, sizeof(prime)); memset(id1, 0, sizeof(id1)); memset(id2, 0, sizeof(id2)); memset(flag, 0, sizeof(flag)); memset(g, 0, sizeof(g)); memset(sum, 0, sizeof(sum)); memset(a, 0, sizeof(a)); ncnt = m = T = n = 0; } inline void init() { T = sqrt(n + 0.5); for (int i = 2; i <= T; i++) { if (!flag[i]) prime[++ncnt] = i, sum[ncnt] = sum[ncnt - 1] + i; for (int j = 1; j <= ncnt && i * prime[j] <= T; j++) { flag[i * prime[j]] = 1; if (i % prime[j] == 0) break; } } for (ll l = 1; l <= n; l = n / (n / l) + 1) { a[++m] = n / l; if (a[m] <= T) id1[a[m]] = m; else id2[n / a[m]] = m; g[m] = calc(a[m]); } for (int i = 1; i <= ncnt; i++) for (int j = 1; j <= m && (ll)prime[i] * prime[i] <= a[j]; j++) g[j] = g[j] - (ll)prime[i] * (g[ID(a[j] / prime[i])] - sum[i - 1]); } inline ll solve(ll x) { if (x <= 1) return x; return n = x, init(), g[ID(n)]; } }a; signed main() { int t; cin >> t; while(t--) { long long n; cin >> n; a.Init(); printf("%lld\n", (2 + n) * (n - 1) / 2 +a.solve(n) - 4); } }