[Codeforces520D] Fun with Integers (规律,并查集)

题目链接:http://codeforces.com/contest/1062/problem/D

给一个n,现在允许任意初始一个数k并给定一个操作:ax=bbx=a当且仅当ab的倍数或ba的倍数时,可以将a变为b(可以是负数),同时获得分数|x|. 要求不允许有多次abba的操作(每个x仅算一次),问最多能得多少分。

看到第一个样例就明白了:考虑一个数x和它的因数pi,我们总可以由x转到所有±pi的可能(从x转到pi,再由pi转到x,然后是xpi,接着是pix),每一次的贡献是4pi,于是我们考虑维护所有带有整除关系的连通块,然后计算它们的所有倍数和*4就可以了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
#include <bits/stdc++.h>
using namespace std;

using LL = long long;
const int maxn = 100100;
int n;
int pre[maxn];
LL s[maxn];

int find(int x) {
return x == pre[x] ? x : pre[x] = find(pre[x]);
}

void unite(int x, int y) {
pre[find(x)] = find(y);
}

signed main() {
// freopen("in", "r", stdin);
while(~scanf("%d", &n)) {
for(int i = 1; i <= n; i++) {
pre[i] = i;
}
memset(s, 0, sizeof s);
for(int i = 2; i <= n; i++) {
for(int j = 2; i * j <= n; j++) {
unite(i, i*j);
}
}
for(int i = 2; i <= n; i++) {
for(int j = 2; i * j <= n; j++) {
s[find(i)] += (LL)j << 2LL;
}
}
LL ret = 0;
for(int i = 1; i <= n; i++) ret = max(ret, s[i]);
printf("%I64d\n", ret);
}
return 0;
}
Powered By Valine
v1.5.2