我使用了to_string()函数,所以提交的时候,请选择c++11标准,不然会出现编译报错。
先附上80分代码,之后再补完整版。
#include<iostream>
#include<vector>
#include<set>
#include<string>
#include<algorithm>
#include<cctype>
using namespace std;
class IP{
public:
string s;
string binary;
int pre;
IP(){
this->binary = "";
}
};
int n;
IP ip[10000];
set<int> del;
void reform(int);
string tobinary(int);
bool cmp(const IP &, const IP &);
void merge();
int main(){
cin >> n;
for(int i = 0; i < n; i++){
cin >> ip[i].s;
reform(i);
}
sort(ip, ip + n, cmp);
merge();
for(int i = 0; i < n; i++){
if(del.find(i) != del.end()) continue;
cout << ip[i].s << '/' << ip[i].pre << endl;
}
return 0;
}
void reform(int i){
int point = count(ip[i].s.begin(), ip[i].s.end(), '.');
int slash = count(ip[i].s.begin(), ip[i].s.end(), '/');
if(point < 3 && slash == 1){
string add = "";
for(int j = point; j < 3; j++){
add += ".0";
}
ip[i].s = ip[i].s.substr(0, ip[i].s.find_first_of('/'))
+ add + ip[i].s.substr(ip[i].s.find_first_of('/'));
}else if(slash == 0){
string add = "";
for(int j = point; j < 3; j++){
add += ".0";
}
ip[i].s = ip[i].s + add + '/' + to_string((point + 1) * 8);
}
for(int j = 0, k = 0; ; ){
if(ip[i].s[k] == '.'){
ip[i].binary += tobinary(atoi(ip[i].s.substr(j, k - j).c_str()));
j = k++ + 1;
}else if(ip[i].s[k] == '/'){
ip[i].binary += tobinary(atoi(ip[i].s.substr(j, k - j).c_str()));
break;
}else{
k++;
}
}
ip[i].pre = atoi(ip[i].s.substr(ip[i].s.find_first_of('/') + 1).c_str());
ip[i].s = ip[i].s.substr(0, ip[i].s.find_first_of('/'));
}
string tobinary(int num){
string res = "";
while(num != 0){
res = (num % 2 == 1 ? "1" : "0") + res;
num /= 2;
}
for(int i = res.length(); i < 8; i++){
res = "0" + res;
}
return res;
}
bool cmp(const IP &a, const IP &b){
if(a.binary != b.binary){
return a.binary < b.binary;
}else{
return a.pre < b.pre;
}
}
void merge(){
if(n == 1) return;
for(int i = 0, j = 1; j < n; j++){
if(ip[i].pre <= ip[j].pre
&& ip[i].binary.substr(0, ip[i].pre)
== ip[j].binary.substr(0, ip[i].pre)){
del.insert(j);
}else{
i = j;
}
}
// if(n - del.size() == 1) return;
// for(int i = 0, j = 1; j < n; ){
// if(del.find(j) != del.end()){
//
// }else{
//
// }
// }
}