演算法競賽入門經典(第2版)習題4-5 IP網路UVa1590
阿新 • • 發佈:2019-02-15
#include <stdio.h> #include <string.h> int twoip[1005][35]; void changetwo(int num, int i, int j) { int q, chu = num; //printf("%d %d %d\n", num, i, j); j = j * 8; for(q = j; q > j-8; q--) { twoip[i][q] = chu % 2; chu = chu / 2; } } void twoten(int left) { int j, i, t[35], v = 0; memset(t, 0, sizeof(t)); for(i = 1; i <= left; i++) t[i] = twoip[1][i]; for(i = 1; i <= 32; i = i + 8) { v = 0; for(j = i; j < i+8; j++) { v = v * 2 + t[j]; } printf("%d", v); if(j < 30) printf("."); } printf("\n"); } void twotenzi(int left) { int j, i, t[35], v = 0; memset(t, 0, sizeof(t)); for(i = 1; i <= left; i++) t[i] = 1; /*for(i = 1; i <= 32; i++) printf("%d", t[i]);*/ //printf("\n"); for(i = 1; i <= 32; i = i + 8) { v = 0; for(j = i; j < i+8; j++) v = v * 2 + t[j]; printf("%d", v); if(j < 30) printf("."); } printf("\n"); } int main() { int n, num, i, j, left = 0; scanf("%d", &n); memset(twoip, 0, sizeof(twoip)); for(num = 1; num <= n; num++) { int t1, t2, t3, t4; scanf("%d.%d.%d.%d", &t1, &t2, &t3, &t4); changetwo(t1, num, 1); changetwo(t2, num, 2); changetwo(t3, num, 3); changetwo(t4, num, 4); } /*for(i = 1; i <= n; i++) { for(j = 1; j <= 32; j++) { printf("%d", twoip[i][j]); } printf("\n"); }*/ for(j = 1; j < 33; j++) { int t, check = 1; for(i = 1; i <= n; i++) { if(i == 1) t = twoip[i][j]; else if(t != twoip[i][j]) check = 0; } if(check) left++; else break; } //printf("%d\n", left); twoten(left); twotenzi(left); return 0; }