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;
}
相关推荐
clint4561 天前
C++进阶(1)——前景提要
c++
夜悊2 天前
C++代码示例:进制数简单生成工具
c++
郝学胜_神的一滴2 天前
CMake 021: IF 条件判据详诠
c++·cmake
_wyt0012 天前
洛谷 B3930 [GESP202312 五级] 烹饪问题 题解
c++·gesp
玖玥拾2 天前
C/C++ 数据结构(七)栈、容器适配器
c语言·数据结构·c++··容器适配器
один but you2 天前
constexpr函数
c++
凡人叶枫2 天前
Effective C++ 条款41:了解隐式接口和编译期多态
java·开发语言·c++·effective c++
凡人叶枫2 天前
Effective C++ 条款42:了解 typename 的双重意义
java·linux·服务器·c++
小胖xiaopangss2 天前
BRpc使用
c++·rpc
-森屿安年-2 天前
63. 不同路径 II
c++·算法·动态规划