This submission is migrated from previous version of oj.uz, which used different machine for grading. This submission may have different result if resubmitted.
#include <bits/stdc++.h>
#ifdef local
#define debug(a...) qqbx(#a, a)
template <typename ...T> void qqbx(const char *s, T ...a) {
int cnt = sizeof...(T);
((std::cerr << "\033[1;32m(" << s << ") = (") , ... , (std::cerr << a << (--cnt ? ", " : ")\033[0m\n")));
}
#define pary(a...) danb(#a, a)
template <typename T> void danb(const char *s, T L, T R) {
std::cerr << "\033[1;32m[ " << s << " ] = [ ";
for (int f = 0; L != R; ++L) std::cerr << (f++ ? " " : "") << *L;
std::cerr << " ]\033[0m\n";
}
#else
#define debug(...) ((void)0)
#define pary(...) ((void)0)
#endif // local
#define all(v) begin(v),end(v)
#define pb emplace_back
using namespace std;
using ll = int64_t;
const int inf = 1e9, MOD = 1000000007, maxn = 1 << 18, maxLg = 18;
struct Trie {
int ch[maxn][2], cnt[maxn], tot;
ll tag[maxLg][2];
int n;
void insert(int x) {
int now = 0;
for (int i = n-1; i >= 0; i--) {
int d = x >> i & 1;
if (!ch[now][d])
ch[now][d] = ++tot;
if (ch[now][!d])
tag[i][!d] += cnt[ch[now][!d]];
now = ch[now][d];
++cnt[now];
}
}
pair<ll,int> getBest() {
ll ans = 0;
int x = 0;
for (int i = 0; i < n; i++) {
if (tag[i][0] < tag[i][1])
ans += tag[i][0];
else
ans += tag[i][1], x ^= 1<<i;
}
return { ans, x };
}
void init() {
memset(ch, 0, sizeof ch);
memset(cnt, 0, sizeof cnt);
memset(tag, 0, sizeof tag);
tot = 0;
}
} trie;
int pos[maxn];
pair<ll,int> calc(int n) {
trie.init();
for (int i = 0; i < (1<<n); i++)
trie.insert(pos[i]);
pary(pos, pos+(1<<n));
return trie.getBest();
}
signed main() {
ios_base::sync_with_stdio(0), cin.tie(0);
int n;
cin >> n;
trie.n = n;
for (int i = 0, x; i < (1<<n); i++) {
cin >> x;
pos[x] = i;
}
if (n == 0)
return cout << 0 << '\n', 0;
ll ans = 1e18;
int bestShift = 0;
int bestX = 0;
for (int shift = 0; shift < n; shift++) {
auto [cost, x] = calc(n);
if (ans > cost) {
ans = cost;
bestShift = shift;
bestX = x;
}
for (int i = 0; i < (1<<n); i++)
pos[i] = (pos[i] >> 1) | ((pos[i] & 1) << (n-1));
}
cout << ans << '\n';
debug(bestX);
string op;
for (int i = 0; i < bestShift; i++)
op += '2';
for (int i = 0; i < n; i++) {
op += '2';
if (~bestX >> i & 1)
op += '1';
}
cout << op << '\n';
}
Compilation message (stderr)
cheerleaders.cpp: In function 'int main()':
cheerleaders.cpp:82:14: warning: structured bindings only available with '-std=c++17' or '-std=gnu++17'
82 | auto [cost, x] = calc(n);
| ^
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |
# | Verdict | Execution time | Memory | Grader output |
---|
Fetching results... |