题意
给出几个IP地址
找最小的范围使得输入全部包含在范围之中
输出该范围的最小IP地址和子网掩码
将ip地址和子网掩码看作二进制
子网掩码前32-n位均为1, 后n位为0
对应ip地址范围前32-n位相同, 后n位可以不同
AC代码
#include <iostream>
#include <algorithm>
#include <cstdio>
#include <cstring>
using namespace std;
const int maxn = 1000+10;
int ip[4][maxn];
int s1[4], s2[4];
int mark[] = {255, 254, 252, 248, 240, 224, 192, 128, 0};
//分别是子网掩码中11111111,11111110,11111100,11111000,...,00000000二进制对应值
int main()
{
int T, i, j, mrk;
int maxip, minip;
while( ~scanf("%d",&T))
{
memset( ip, 0, sizeof(ip) );
memset( s1, 0, sizeof(s1) );
memset( s2, 0, sizeof(s2) );
for( i = 0; i < T; i++ )
scanf("%d.%d.%d.%d",&ip[0][i],&ip[1][i],&ip[2][i],&ip[3][i]);
for( i = 0; i < 4; i++)
{
mrk = 0;
sort(ip[i], ip[i]+T);
maxip = ip[i][T-1], minip = ip[i][0];
for(j = 0; j < 8; j++)
{
if(maxip % 2 != minip % 2)
mrk = j+1;
maxip /= 2, minip /= 2;
}
s2[i] = mark[mrk];
s1[i] = ip[i][0] & s2[i];
}
for( i = 0; i < 4; i++ ){
if(s2[i] != mark[0]){
for( i = i + 1; i < 4; i++){
s2[i] = 0;
s1[i] = 0;
}
break;
}
}
printf("%d.%d.%d.%d
",s1[0], s1[1], s1[2], s1[3]);
printf("%d.%d.%d.%d
",s2[0], s2[1], s2[2], s2[3]);
}
return 0;
}