This topic is a topic about IP address, in order to understand the problem in depth needs to have a certain network foundation.
The first time I did this topic, although also AC, but the code is more complex, not enough refining. Recently participated in the network training, on the basis of a certain knowledge, but also rewrite the problem. Many steps are simplified by bitwise operations (such as SHIFT, XOR), where the code is pasted two times before and after.
Second time code:
1#include <cstdio>2 Const intMAXN = ++Ten;3 intips[maxn][4];4 intFind_firstdiff (intm) {5 for(intI=0;i<4; i++)6 for(intj=0; j<m;j++)7 if(ips[j][i]!=ips[0][i])returni;8 return 3;9 }Ten voidPrintip (intSerintEquintk) { One intis_first=0; A for(intI=0;i<4; i++){ - if(Is_first) printf (".");Elseis_first=1; - if(i==k) printf ("%d", equ); the Else if(i<k) printf ("%d", ser==-1? ips[0][i]:ser); - Elseprintf"0"); - } -printf"\ n"); + } - intMain () { + intm; A while(SCANF ("%d", &m)! =EOF) { at for(inti =0; I < m; i++) -scanf"%d.%d.%d.%d", &ips[i][0],&ips[i][1],&ips[i][2],&ips[i][3]); - intK =Find_firstdiff (m); - intMaxi=0, mini=0; - for(inti =0; I < m; i++){ - if(Ips[maxi][k] < ips[i][k]) maxi=i; in if(Ips[mini][k] > ips[i][k]) mini=i; - } to intC=0, t=Ips[maxi][k]; + if(maxi!=Mini) { - intD = ips[maxi][k] ^Ips[mini][k]; theC=0; * if(!d) c=1; $ Else while(d) {Panax NotoginsengD/=2; -C++; the } +t= Ips[maxi][k] >>c <<C; A } thePrintip (-1, t,k); +Printip (255, the-(1<<c), K); - } $ return 0; $}
First time Code:
1#include <cstdio>2#include <cstring>3 #defineMAXN 1000+54 ints[maxn][5];5 voidGetbit (int*s,intnum) {6 intn=7;7 while(num) {8s[n--]=num%2;9Num/=2;Ten } One A } - intMain () { - intN; the while(SCANF ("%d", &n) = =1){ - intnetmask[5]={0}; - intip[5]={0}; - intmax,min; + for(intI=0; i<n;i++){ -scanf"%d.%d.%d.%d", &s[i][0],&s[i][1],&s[i][2],&s[i][3]); + } A intok=1, same=0; at intK; - for(k=0;k<4; k++){ -max=s[0][k],min=s[0][k]; - for(intI=0; i<n;i++){ - if(i&&ok&&s[i][k]!=s[i-1][k]) { -ok=0; same=K; in } - if(S[i][k]>max) max=S[i][k]; to Else if(s[i][k]<min) min=S[i][k]; + } - if(!ok) Break; theip[k]=s[0][k]; *netmask[k]=255; $ }Panax Notoginseng inta[Ten]={0}; - intc=max^min,sum1=0, sum2=0, sp=0; the for(intI=0;i<8; i++){ + if(C>= (1<<i) &&c< (1<< (i+1))){ Asp=i+1; Break; the } + } - getbit (a,min); $ for(intI=0;i<8-sp;i++){ $sum1=sum1+ (a[i]* (1<< (7-i))); -sum2+= (1*(1<< (7-i))); - } theip[k]=sum1; -netmask[k]=sum2;Wuyiprintf"%d.%d.%d.%d\n", ip[0],ip[1],ip[2],ip[3]); theprintf"%d.%d.%d.%d\n", netmask[0],netmask[1],netmask[2],netmask[3]); - } Wu return 0; -}
Uva 1590 IP Networks