跳到正文

题解

AT_arc161_b 题解

shinzAnmono约 4 分钟
原文
文章信息与版本

文章信息

发布
2023年5月29日
收录
2025年12月12日
更新
2026年11月6日
篇幅
约 4 分钟

版本

  1. v1当前

[ARC161B] Exactly Three Bits

首先,我们可知,n<7n<7 时,是绝对不可能有解的。

然后我们对每个 nn 转成二进制串 ss,然后进行分类讨论。

  1. popcount(s)=1\mathrm{popcount}(s)=1,也就是说二进制串的形式是 100⋯00n个01\underset{n个0}{00\cdots00},那么我们可以那么答案便是 11100⋯00n−4个0111\underset{n-4个0}{00\cdots00}
  2. popcount(s)=2\mathrm{popcount}(s)=2 且第二个 11 在字符串末尾,这个答案同第一种情况。
  3. popcount(s)=2\mathrm{popcount}(s)=2 且第二个 11 不在字符串末尾,我们找到第二个 11 的位置 pp,将 sps_p 改为 00,sp+1s_{p+1} 和 sp+2s_{p+2} 改为 11(由于 ss 是字符串,所以 ii 越大,sis_i 的位数越低)。
  4. popcount(s)≥3\mathrm{popcount}(s)\geq3,我们找到第三个 11 的位置 pp,然后将 [p+1,len(s)][p+1,\mathrm{len}(s)] 全部变为 00。

我们对二进制串 ss 进行操作,最后将 ss 转为十进制。这里介绍一个函数:

long long stoll(const std::string &__str, std::size_t *__idx, int __base)

这个函数可以将字符串转为 long long 型,__idx 一般使用 nullptr,base 是字符串的进制,默认为 1010 进制转换。

给出代码:

C++
#include<iostream>
#include<algorithm>
#include<string>
#include<stack>
using ll = long long;
int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);
    int t;
    std::cin >> t;
    while (t--) {
        ll n;
        std::cin >> n;
        if (n < 7) std::cout << "-1\n";
        else {
            std::stack<ll> s;
            std::string bit;
            if (n < 7) std::cout << "-1\n";
            ll cx = n;
            while (cx)
                s.push(cx % 2), cx /= 2ll;
            while (!s.empty()) 
                bit += s.top() + '0', s.pop();
            int cnt = 0;
            for (char c: bit) 
                if (c == '1') cnt++;
            if (cnt < 3) {
                if (cnt == 1) bit = "111" + std::string(bit.length() - 4, '0');
                else {
                    int pos = bit.find('1', bit.find('1') + 1);
                    if (pos > bit.length() - 3) 
                        bit = "111" + std::string(bit.length() - 4, '0');
                    else bit[pos] = '0', bit[pos + 1] = bit[pos + 2] = '1';
                }
            }
            else {
                int pos = bit.find('1', bit.find('1', bit.find('1') + 1) + 1);
                for (int i = pos + 1; i < bit.size(); i++) bit[i] = '0';
            }
            std::cout << std::stoll(bit, nullptr, 2) << "\n";
        }
    }
    return 0;
}
原文