Repository navigation
Expand file tree
/
Copy path1689E-E-ANDfinity.cpp
More file actions
124 lines (102 loc) · 2.69 KB
/
Copy path1689E-E-ANDfinity.cpp
File metadata and controls
124 lines (102 loc) · 2.69 KB
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
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
//url:https://codeforces.com/contest/1689/problem/E
//time:2022-06-10 20:13:48
//name:E-ANDfinity
#include <bits/stdc++.h>
using i64 = long long;
struct DSU {
std::vector<int> f, siz;
DSU(int n) : f(n), siz(n, 1) { std::iota(f.begin(), f.end(), 0); }
int leader(int x) {
while (x != f[x]) x = f[x] = f[f[x]];
return x;
}
bool same(int x, int y) { return leader(x) == leader(y); }
bool merge(int x, int y) {
x = leader(x);
y = leader(y);
if (x == y) return false;
siz[x] += siz[y];
f[y] = x;
return true;
}
int size(int x) { return siz[leader(x)]; }
};
void solve() {
int n;
std::cin >> n;
std::vector<int> a(n);
for (int i = 0; i < n; i++) {
std::cin >> a[i];
}
auto work = [&](auto a) {
DSU dsu(30);
std::vector<bool> use(30);
int ans = 0;
int t = 30;
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
a[i]++;
ans++;
}
int x = __builtin_ctz(a[i]);
for (int j = x; j < 30; j++) {
if (a[i] >> j & 1) {
use[j] = true;
dsu.merge(x, j);
}
}
t = std::min(t, x);
}
bool ok = true;
for (int i = 0; i < 30; i++) {
if (use[i] && !dsu.same(t, i)) {
ok = false;
}
}
if (ok) {
return std::pair(ans, a);
}
for (int i = 0; i < n; i++) {
int x = __builtin_ctz(a[i]);
if (t > 0) {
t = 0;
a[i]++;
ans++;
dsu.merge(0, x);
}
if (!dsu.same(0, x)) {
a[i]++;
ans++;
dsu.merge(0, x);
}
}
return std::pair(ans, a);
};
auto ans = work(a);
for (int i = 0; i < n; i++) {
if (a[i] == 0) {
continue;
}
a[i]--;
auto res = work(a);
a[i]++;
res.first++;
if (res.first < ans.first) {
ans = res;
}
}
std::cout << ans.first << "\n";
for (int i = 0; i < n; i++) {
std::cout << ans.second[i] << " \n"[i == n - 1];
}
}
int main() {
std::ios::sync_with_stdio(false);
std::cin.tie(nullptr);
int t;
std::cin >> t;
while (t--) {
solve();
}
return 0;
}