题解 | 特工身份识别系统(掩码)

特工身份识别系统

https://www.nowcoder.com/practice/f591698ed62a40cf92500abfb6b0b231

#include <iostream>
#include <vector>
#include <string>
#include <algorithm>
#include <cstdint>

bool is_authorized(const std::pair<uint64_t, uint32_t>& rule, const uint64_t code) {
    if (rule.second == 0) return true;
    const uint64_t mask = (rule.second == 48) ? 0xFFFFFFFFFFFFULL : ((1ULL << rule.second) - 1) << (48 - rule.second);
    return (rule.first & mask) == (code & mask);
}

int main() {
    std::ios::sync_with_stdio(false);
    std::cin.tie(nullptr);

    int n;  // 授权规则个数
    std::cin >> n;
    std::cin.ignore();

    std::vector<std::pair<uint64_t, uint32_t>> rules;  // 授权规则(处理后的)
    rules.reserve(n);

    // 输入授权规则
    for (int i = 0; i < n; ++i) {
        // 读取授权规则并处理
        std::string code_string_raw, code_string, m_string;
        std::getline(std::cin, code_string_raw, '/');
        std::getline(std::cin, m_string);
        code_string.reserve(12);
        std::copy_if(code_string_raw.begin(), code_string_raw.end(),
            std::back_inserter(code_string), [](const char c) { return c != '-'; });

        // 进制转换
        rules.emplace_back(std::stoll(code_string, nullptr, 16), std::stoi(m_string));
    }

    int m;  // 身份代号个数
    std::cin >> m;
    std::cin.ignore();

    // 身份验证
    for (int i = 0; i < m; ++i) {
        // 输入身份代号并处理
        std::string code_string_raw, code_string;
        std::getline(std::cin, code_string_raw);
        code_string.reserve(12);
        std::copy_if(code_string_raw.begin(), code_string_raw.end(),
            std::back_inserter(code_string), [](const char c) { return c != '-'; });

        // 进制转换
        const uint64_t code = std::stoll(code_string, nullptr, 16);

        // 身份验证
        bool authorized = false;
        for (const auto& rule : rules) {
            if (is_authorized(rule, code)) {
                authorized = true;
                break;
            }
        }
        std::cout << (authorized ? "YES" : "NO") << std::endl;
    }

    return 0;
}

全部评论

相关推荐

09-13 08:41
服装/纺织设计
那一天的Java_J...:你第一次参加面试吗
点赞 评论 收藏
分享
评论
2
1
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务