1590 - IP Networks (UVA)

题目链接如下:

Online Judge

学习了bitset,很强大。我的代码如下:

cpp 复制代码
#include <cstdio>
#include <string>
#include <vector>
#include <bitset>
// #define debug

int m;
int byte[4], mask[4];
std::vector<std::string> vec;

int main(){
    #ifdef debug
    freopen("0.txt", "r", stdin);
    freopen("1.txt", "w", stdout);
    #endif
    while(scanf("%d", &m) == 1){
        vec.clear();
        while(m--){
            std::string s;
            for(int i = 0; i < 4; ++i){
                scanf("%d", &byte[i]);
                std::bitset<8> bitset1(byte[i]);
                s += bitset1.to_string();
                getchar();
            }
            vec.push_back(s);
        }
        int k = 32;
        for(int i = 0; i < 32; ++i){
            for(int j = 1; j < vec.size(); ++j){
                if(vec[j][i] != vec[0][i]){
                    k = i;
                    i = 32;
                    break;
                }
            }
        }
        for(int i = 0; i < 4; ++i){
            byte[i] = 0;
            mask[i] = 0;
            for(int j = 0; j < 8; ++j){
                if(i * 8 + j < k){
                    byte[i] = 2 * byte[i] + vec[0][i * 8 + j] - '0';
                    mask[i] = 2 * mask[i] + 1;
                } else{
                    byte[i] = 2 * byte[i];
                    mask[i] = 2 * mask[i];
                }
            }
            printf("%d%s", byte[i], i == 3 ? "\n" : ".");
        }
        for(int i = 0; i < 4; ++i){
            printf("%d%s", mask[i], i == 3 ? "\n" : ".");
        }
    }
    #ifdef debug
    fclose(stdin);
    fclose(stdout);
    #endif
    return 0;
}
相关推荐
感哥14 小时前
C++ 多态
c++
沐怡旸21 小时前
【底层机制】std::string 解决的痛点?是什么?怎么实现的?怎么正确用?
c++·面试
River4161 天前
Javer 学 c++(十三):引用篇
c++·后端
感哥1 天前
C++ std::set
c++
侃侃_天下1 天前
最终的信号类
开发语言·c++·算法
博笙困了1 天前
AcWing学习——差分
c++·算法
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(2)
c++·设计模式·抽象工厂模式
青草地溪水旁1 天前
设计模式(C++)详解—抽象工厂模式 (Abstract Factory)(1)
c++·设计模式·抽象工厂模式
感哥1 天前
C++ std::vector
c++
zl_dfq1 天前
C++ 之【C++11的简介】(可变参数模板、lambda表达式、function\bind包装器)
c++