天天看點

CCF認證 201812-3 CIDR合并

#include <iostream>
#include <algorithm>
#include <cstring>
#include <vector>
using namespace std;
const int N = 100005;
int cnt;
struct IP{ 
    string info;
    unsigned int val;
    int a[4], len;
    bool operator< (const IP & others)const{//重載運算符
        return val != others.val? val < others.val: len < others.len;
    }
    void init(IP others){//同級合并得到a'
        val = others.val, len = others.len - 1;
        for(int i = 0; i < 4; i ++) a[i] = others.a[i];
        info = others.info.substr(0, others.info.find('/') + 1) + to_string(len);
    }
    void norm(){//标準化
        int pos = info.find('/'), counts = count(info.begin(), info.end(), '.');
        if(pos == string::npos)
            info += ("/" + to_string((counts + 1) * 8));
        for(int i = 0; i < 3 - counts; i ++)
            info.insert(info.find('/'), ".0");
    }
    void discrate(){//分離具體資訊
        len = stoi(info.substr(info.find('/') + 1));
        string str = info.substr(0, info.find('/'));
        int last = -1;
        val = 0;
        for(int i = 0, now = str.find_first_of('.', last + 1); i < 4; i ++){
            a[i] = stoi(str.substr(last + 1, now - last - 1));
            val = val * 256 + (unsigned int)a[i];
            if(now == str.size()) break;
            last = now, now = str.find_first_of('.', last + 1);
            if(now == string::npos) now = str.size();
        }
    }
    bool legal(){//判斷合法性
        return val >> (32 - len) << (32 - len) == val;
        //return (val >> (32 - len - 1) & 1) ^ 1;
    }
    void interval(unsigned int& l, unsigned int& r){//一個ip位址所比對的所有位址區間
        l = val;
        r = val | (unsigned int)((1ull << (32 - len)) - 1);
    }
}v[N];
bool sub_union(IP ip1, IP ip2, IP& ip){
    if(ip1.len != ip2.len) return false;
    ip.init(ip1);
    if(!ip.legal()) return false;
    unsigned int l, r, l1, r1, l2, r2;
    ip.interval(l, r), ip1.interval(l1, r1), ip2.interval(l2, r2);
    if(r1 + 1 == l2 && l == l1 && r == r2) return true;
    return false;
}
void Union1(){
    int x = 0;
    for(int i = 1; i < cnt; i ++){
        unsigned int l1, r1, l2, r2;
        v[x].interval(l1, r1), v[i].interval(l2, r2);
        if(!(l1 <= l2 && r2 <= r1)) v[++ x] = v[i];
    }
    cnt = x + 1;
}
void Union2(){
    int x = 0;
    IP res; 
    for(int i = 1; i < cnt; i ++){
        if(sub_union(v[x], v[i], res)){
            v[x] = res;
            while(x > 0 && sub_union(v[x - 1], v[x], res))
                v[-- x] = res;
        }
        else v[++ x] = v[i];
    }
    cnt = x + 1;
}
int main(){
    ios::sync_with_stdio(false); cin.tie(0), cout.tie(0);
    int n;
    cin >> n;
    for(int i = 0; i < n; i ++){
        cin >> v[i].info;
        v[i].norm(), v[i].discrate(); 
    }
    sort(v, v + n);
    cnt = n;
    Union1(), Union2();
    for(int i = 0; i < cnt; i ++)
        cout << v[i].info << endl;
    return 0;
}