当初被这道题吓到了,其实是个水题。。。懒的写函数了,直接各种循环。
#include<iostream> #include<cstring> #include<cstdio> #define MAXN 1010 using namespace std; int main() { // freopen("in.txt", "r", stdin); int m, p[5], n = 0, d = 1 << 8; char ip[MAXN][8 * 4 + 10], final_ip[32]; while(cin >> m) { memset(p, 0, sizeof(0)); memset(ip, 0, sizeof(0)); memset(final_ip, 0, sizeof(0)); int max_len = 32; for(int i = 1; i <= m; i++) { scanf("%d.%d.%d.%d", &p[1], &p[2], &p[3], &p[4]); ip[i][32] = '\0'; for(int j = 31; j >= 0; j--) { ip[i][j] = p[j / 8 + 1] % 2; p[j / 8 + 1] /= 2; } } for(int i = 1; i < m; i++) for(int j = i + 1; j <= m; j++) for(int k = 0; k < 32; k++) if(ip[i][k] != ip[j][k]) { if(k < max_len) max_len = k; break; } for(int i = max_len; i < 32; i++) ip[1][i] = 0; for(int i = 0; i < 32; i++) i < max_len ? final_ip[i] = 1 : final_ip[i] = 0; for(int i = 0; i < 32; i++) { d /= 2; n += ip[1][i] * d; if(d == 1) { cout << n; n = 0; d <<= 8; if(i != 31) cout << "."; } } cout << endl; for(int i = 0; i < 32; i++) { d /= 2; n += final_ip[i] * d; if(d == 1) { cout << n; n = 0; d <<= 8; if(i != 31) cout << "."; } } cout << endl; } return 0; }