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;
}
相关推荐
tankeven3 小时前
HJ176 【模板】滑动窗口
c++·算法
OxyTheCrack3 小时前
【C++】一文详解C++智能指针自定义删除器(以Redis连接池为例)
c++·redis
whitelbwwww4 小时前
C++基础--类型、函数、作用域、指针、引用、文件
开发语言·c++
leaves falling4 小时前
C/C++ const:修饰变量和指针的区别(和引用底层关系)
c语言·开发语言·c++
tod1134 小时前
深入解析ext2文件系统架构
linux·服务器·c++·文件系统·ext
不想写代码的星星4 小时前
C++ 类型萃取:重生之我在幼儿园修炼类型学
c++
比昨天多敲两行4 小时前
C++11新特性
开发语言·c++
xiaoye-duck4 小时前
【C++:C++11】核心特性实战:详解C++11列表初始化、右值引用与移动语义
开发语言·c++·c++11
睡一觉就好了。4 小时前
二叉搜索树
c++
whitelbwwww4 小时前
C++进阶--类和模板
c++