简单解法
判断两个IP是否属于同一子网
http://www.nowcoder.com/questionTerminal/34a597ee15eb4fa2b956f4c595f03218
#include<string>
#include<iostream>
#include<vector>
using namespace std;
bool ismask(int a,int b,int c,int d);
bool isip(int a,int b,int c,int d);
int main(){
int a,b,c,d;
char ch;
while(cin>>a>>ch>>b>>ch>>c>>ch>>d){
int a1,b1,c1,d1;
int a2,b2,c2,d2;
cin >> a1 >> ch >> b1>>ch>>c1>>ch>>d1;
cin>>a2>>ch>>b2>>ch>>c2>>ch>>d2;
//cout << a1 << " " << b1 << " " << " " << c1 << " " << d1 << endl;
//cout << a2 << " " << b2 << " " << " " << c2 << " " << d2 << endl;
if(ismask(a,b,c,d)&&isip(a1,b1,c1,d1)&&isip(a2,b2,c2,d2)){
vector<int> res1;
vector<int> res2;
//cout << (a1&a) << endl;
res1.push_back((a1&a));
res1.push_back((b1&b));
res1.push_back((c1&c));
res1.push_back((d1&d));
res2.push_back((a2&a));
res2.push_back((b2&b));
res2.push_back((c2&c));
res2.push_back((d2&d));
bool flag=true;
for(int i=0;i<4;i++){
if(res1[i]!=res2[i]){
flag=false;
}
//cout << res1[i] << " " << res2[i] << endl;
}
if(flag==true){
cout << "0" << endl;
}
else{
cout << "2" << endl;
}
res1.clear();
res2.clear();
}
else{
cout << "1" << endl;
}
}
return 0;
}
bool ismask(int a,int b,int c,int d){
if((a==254||a==252||a==248||a==240||a==224||a==192||a==128)&&b==0&&c==0&&d==0){
return true;
}
else if(a==255&&(b==254||b==252||b==248||b==240||b==224||b==192||b==128||b==0)&&c==0&&d==0){
return true;
}
else if(a==255&&b==255&&(c==254||c==252||c==248||c==240||c==224||c==192||c==128||c==0)&&d==0){
return true;
}
else if(a==255&&b==255&&c==255&&(d==254||d==252||d==248||d==240||d==224||d==192||d==128||d==0)){
return true;
}
return false;
}
bool isip(int a,int b,int c,int d){
if((a>=0&&b<=255)&&(b>=0&&b<=255)&&(c>=0&&c<=255)&&(d>=0&&d<=255)){
return true;
}
return false;
}
