【习题 4-5 Uva1590】 IP Networks

【链接】 我是链接,点我呀:)
【题意】


在这里输入题意

【题解】


假设从第i位开始有不一样的。
那么就把i+1..32位全都置0.
掩码的话类似。前i为全为1,后面32-i位全0.
尽量让后面的连续0(等于掩码最后的0的个数)晚一点出现。
这样网络表示的范围比较小(可供变化的范围比较小)。

【代码】

#include <bits/stdc++.h>
#define rep1(i,a,b) for (int i = a;i <= b;i++)
#define rep2(i,a,b) for (int i = a;i >= b;i--)
using namespace std;

const int N = 1e3;

int n;
string ips[N+10];

string get_format(string s){
    string temp = "";
    int x = 0;
    rep1(i,1,32){
        x = x*2+(s[i-1]-'0');
        if (i%8==0){
            string temp1 = "";
            if (x==0) temp1 = "0";
            while (x>0){
                temp1 =(char)(x%10+'0')+temp1;
                x/=10;
            }
            temp = temp + temp1;
            if (i<32) temp+=".";
        }
    }
    return temp;
}

int main(){
    //freopen("/home/ccy/rush.txt","r",stdin);
   // freopen("/home/ccy/rush_out.txt","w",stdout);
    ios::sync_with_stdio(0),cin.tie(0);
    while (cin >> n){
        rep1(i,1,n){
            ips[i]="";
            string s;
            cin >> s;s+=".";
            int x= 0;
            rep1(j,0,(int)s.size()-1){
                if (s[j]=='.'){
                    string temp = "";
                    rep1(k,1,8){
                        int temp1 = x%2;
                        temp = (char)(temp1+'0')+temp;
                        x/=2;
                    }
                    ips[i]+=temp;
                    x = 0;
                }else{
                    x = x*10+s[j]-'0';
                }
            }
            //cout<<ips[i]<<endl;
        }
        string ans1 = "";
        string ans2 = "";
        for (int i = 0;i < 32;i++){
            int ok = 1;
            rep1(j,1,n)
                if (ips[j][i]!=ips[1][i])
                    ok = 0;
            if (ok){
                ans1 = ans1 + ips[1][i];
                ans2 = ans2 + "1";
            }else{
                rep1(j,i,31) {
                    ans1+="0";
                    ans2+="0";
                }
                break;
            }
        }
        //cout<<ans1<<endl;
        //cout<<ans2<<endl;
        cout<<get_format(ans1)<<endl;
        cout<<get_format(ans2)<<endl;
    }
    return 0;
}

转载于:https://www.cnblogs.com/AWCXV/p/9874744.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值