码迷,mamicode.com
首页 > 其他好文 > 详细

uva1590

时间:2018-05-11 15:32:19      阅读:166      评论:0      收藏:0      [点我收藏+]

标签:uva   eof   cin   turn   clu   cout   mini   while   using   

将IP地址分4段处理,先进行排序,找到最大值和最小值的相同最小字节数,通过tables得到对应段的zwym[i],通过zwym[i]&ip[i][0],ip[i][0]是经过排序后该分段最小值,得到minip[i]。最后将子网掩码不是255分段的后续IP段清零。

#include<iostream>
#include<cstring>
#include<algorithm>

using namespace std;

int tables[9] = { 255,254,252,248,240,224,192,128,0 };
int main()
{
	int zwym[4], minip[4], m, ip[4][1024];
	while (cin >> m) {
		memset(ip, 0, sizeof(ip));
		for (int i = 0; i < m; i++) {
			char t[40];
			cin >> t;
			int begin = 0, ipnum = 0;
			for (int j = 0; j < strlen(t); j++) {
				if (t[j] == ‘.‘) {
					for (; begin < j; begin++)
						ip[ipnum][i] = ip[ipnum][i] * 10 + int(t[begin] - ‘0‘);
					begin++;
					ipnum++;
				}
			}
			for (; begin < strlen(t); begin++)
				ip[ipnum][i] = ip[ipnum][i] * 10 + int(t[begin] - ‘0‘);
		}
		for (int i = 0; i < 4; i++) {
			int dif = 0, p, q;
			sort(ip[i], ip[i] + m);
			p = ip[i][0];
			q = ip[i][m - 1];
			for (int j = 1; j < 9; j++) {
				if (p % 2 != q % 2) {
				//if ((p % 2) != (q % 2)) {
					dif = j;
				}
				p = p / 2;
				q = q / 2;
			}
			zwym[i] = tables[dif];
			minip[i] = ip[i][0] & zwym[i];
		}
		for (int i = 0; i < 4; i++) {
			if (zwym[i] != 255) {
				for (i = i + 1; i < 4; i++) {
					zwym[i] = 0;
					minip[i] = 0;
				}
				break;
			}
		}
		cout << minip[0] << ‘.‘ << minip[1] << ‘.‘ << minip[2] << ‘.‘ << minip[3] << endl;
		cout << zwym[0] << ‘.‘ << zwym[1] << ‘.‘ << zwym[2] << ‘.‘ << zwym[3] << endl;
	}	
	return 0;
}

  

uva1590

标签:uva   eof   cin   turn   clu   cout   mini   while   using   

原文地址:https://www.cnblogs.com/ArvinShaffer/p/9024678.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!