CSP CIDR合并 40分

TODO: 用pair做来排序会更方便

#include <iostream>
#include <unordered_map>
#include <algorithm>
#include<vector>

using namespace std;

const int N = 1e5 + 10;

int n;
string str;
struct IP{
    string ips;
    int pre;
}ip[N];

int str_to_int(string a)
{
    int loc = a.find('.');
    int shu = atoi(a.substr(0,loc).c_str());
    // 第二层怎么判断呢?居然能拿四十分
    return shu;
}

int comp(const IP &a,const IP &b)
{
    if (str_to_int(a.ips) != str_to_int(b.ips)) return str_to_int(a.ips) < str_to_int(b.ips);//先比较第一个关键字,从大到小排序
    return a.pre > b.pre;//比较第二个关键字,从小到大排序
}

int main()
{
    cin >> n;
    for(int i=0;i < n;i++)
    {
        cin >> str;
        int num = count(str.begin(),str.end(),'.');
        int loc = str.find('/');
        int len = str.size();
        if(num == 3 && loc != -1) // 标准型
        {
            int s1 = atoi(str.substr(loc+1,len-loc).c_str());
            str = str.substr(0,loc);
            ip[i].ips = str,ip[i].pre = s1;
            // cout << str << " " << s1 << endl;
        }
        else if(loc == -1) // 省略长度型
        {
            if(num == 3)    ip[i].ips = str,ip[i].pre = 32;
            else if(num == 2)   str += ".0",ip[i].ips = str,ip[i].pre = 24;
            else if(num == 1)   str += ".0.0",ip[i].ips = str,ip[i].pre = 16;
            else str += ".0.0.0",ip[i].ips = str,ip[i].pre = 8;
        }
        else // 省略后缀型 ,感觉存在很大的重复
        {
            int s1 = atoi(str.substr(loc+1,len-loc).c_str());
            str = str.substr(0,loc); // 易错点
            if(num == 3)    ;
            else if(num == 2)   str += ".0";
            else if(num == 1)   str += ".0.0";
            else str += ".0.0.0";
            ip[i].ips = str,ip[i].pre = s1;
        }
    }
    // 输入结束
    // 开始排序

    sort(ip,ip+n,comp);
    for(int i=0;i < n;i++)
    {
        cout << ip[i].ips << "/" << ip[i].pre << endl;
        
    }
    
    // 通过匹配集和等价的含义来处理合并
    
    return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值