原题链接:CCF-CSP 201812-3 CIDR合并
参考博客:CSP认证201812-3 CIDR合并(超详细解析—大模拟)
先码在这,100分的输出逻辑我还有点没想通。。
#include <bits/stdc++.h>
using namespace std;
#define ll unsigned long long
const int N=1e5+10;
struct Node
{
int a3,a2,a1,a0,len;
ll ip;
friend bool operator < (const Node& a,const Node& b)
{
if(a.ip!=b.ip) return a.ip>b.ip;
else return a.len>b.len;
}
};
priority_queue<Node> q;
vector<int> change(string s)
{
vector<int> v;
int len=0,i=0,f=1;
while(i<s.size() && s[i]!='/') i++;
if(i==s.size()) f=0;
else
{
string tmp=s.substr(i+1);
len=atoi(tmp.c_str());
s=s.substr(0,i);
}
stringstream ss(s);
string t;
while(getline(ss,t,'.'))
{
int num=atoi(t.c_str());
v.push_back(num);
}
int vlen=v.size();
if(f==0) len=8*vlen;
while(vlen<4)
{
v.push_back(0);
vlen++;
}
v.push_back(len);
return v;
}
//第二步 从小到大合并
bool check(Node a,Node b)
{
if(a.ip>b.ip) return false;
int len=a.len;
if((a.ip>>(32-len))!=(b.ip>>(32-len))) return false;
return true;
}
//第三步 同级合并
bool check2(Node a,Node b)
{
if(a.len!=b.len) return false;
int len=a.len;
if((a.ip>>(32-len+1))!=(b.ip>>(32-len+1))) return false;
if((a.ip>>(32-len+1))%2!=0) return false;
if((b.ip>>(32-len+1))%2==1) return true;
}
int main()
{
std::ios::sync_with_stdio(false);
std::cin.tie(0);
std::cout.tie(0);
int n; cin>>n;
string s;
for(int i=0;i<n;i++)
{
cin>>s;
vector<int> v=change(s);
Node x;
x.a3=v[0];
x.a2=v[1];
x.a1=v[2];
x.a0=v[3];
x.len=v[4];
x.ip=x.a0+x.a1*256+x.a2*256*256+x.a3*256*256*256;
q.push(x);
}
vector<Node> res;
Node x,y;
x=q.top(); q.pop();
res.push_back(x);
while(!q.empty())
{
y=q.top();
q.pop();
if(!check(x,y))
{
res.push_back(y); x=y;
}
}
for(int i=0;i<res.size();i++)
{
x=res[i];
cout<<x.a3<<"."<<x.a2<<"."<<x.a1<<"."<<x.a0<<"/"<<x.len<<endl;
}
return 0;
}