POJ-2799(找到一组IP的最小网络)

来源:互联网 发布:怎样申请淘宝开网店 编辑:程序博客网 时间:2024/06/05 21:56

题目:http://poj.org/problem?id=2799

思路:找出IP的最长公共前缀即最小网络,长度即子网掩码全1的长度


#include <cstdio>#define MAX1005int main(){unsigned n, i, a, b, c, d, ip, net;int len;while(scanf("%u", &n) == 1){scanf("%u.%u.%u.%u", &a, &b, &c, &d);net = a << 24 | b << 16 | c << 8 | d;len = 32;for(i = 1; i < n; ++i){scanf("%u.%u.%u.%u", &a, &b, &c, &d);ip = a << 24 | b << 16 | c << 8 | d;//find longest common prefix between ip and netint b = 31;for(; b >= 32-len; --b){if((net & (1u << b)) ^ (ip & (1u << b))) break;}//update common prefixlen = 31 - b;}//first len bits are 1unsigned mask = 0;for(int b = 31; b >= 32-len; --b) mask |= 1 << b;net &= mask;printf("%u.%u.%u.%u\n", net >> 24 & 255, net >> 16 & 255, net >> 8 & 255, net & 255);printf("%u.%u.%u.%u\n", mask >> 24 & 255, mask >> 16 & 255, mask >> 8 & 255, mask & 255);}return 0;}


0 0
原创粉丝点击