我是把ip地址转成32位的二进制,然后XOR,看到比较短的那个掩码的位数是不是都是0,但是只过了60多,不知道为什么。
#include <iostream>
#include <cstdio>
#include <map>
#include <string>
#include <sstream>
#include <vector>
#include <set>
#include <bitset>
using namespace std;
ostringstream ostr;
struct ip_addr {
bitset<32> s1,s2,s3,s4;
unsigned int l;
bitset<32> bin;
};
int main(){
int n= 0;
cin >> n;
vector<ip_addr> ips;
vector<string> ipstring;
set<int> idx;
for(int i = 0; i < n; i++){
ip_addr ip;
unsigned int s1,s2,s3,s4,l;
scanf("%d.%d.%d.%d/%d",&s1,&s2,&s3,&s4,&ip.l);
ip.s1 = bitset<32>(s1);
ip.s2 = bitset<32>(s2);
ip.s3 = bitset<32>(s3);
ip.s4 = bitset<32>(s4);
ip.bin = ((ip.s1<<8 | ip.s2)<<8 | ip.s3)<<8 | ip.s4;
ips.push_back(ip);
bool flag =false;
for(auto j:idx){
ip_addr tmp = ips[j];
unsigned int tmp_l = tmp.l;
bool current_wider = tmp.l>ip.l;
unsigned int len = current_wider?ip.l:tmp.l;
string compare="00000000000000000000000000000000";
string _xor = (tmp.bin^ip.bin).to_string();
if(compare.substr(0,len) == _xor.substr(0,len)){
if(current_wider){
idx.erase(j);
}
else{
flag = true;
}
}
}
if(flag){
continue;
}
idx.insert(i);
}
cout<<idx.size()<<endl;
for(auto j:idx){
ip_addr ip = ips[j];
cout<<ip.s1.to_ulong()<<'.'<<ip.s2.to_ulong()<<'.'<<ip.s3.to_ulong()<<'.'<<ip.s4.to_ulong()<<'/'<<ip.l<<endl;
}
return 0;
}