【模拟】UVA1590 求助
查看原帖
【模拟】UVA1590 求助
481330
sunyizhe还是MC大佬楼主2023/9/3 15:28
//程序算法:模拟,计算机知识
#include <bits/stdc++.h>
using namespace std;
const int N=1e3+10;

string IP[N],ans1="",ans2="";//ans1:网络地址 ans2:网络掩码
void fast_read()
{
	ios::sync_with_stdio(false);
	cin.tie(0);
	cout.tie(0);
}

string IntTo8Bin(int x)
{
	string s="";
	if(x==0)s="0";
	while(x)
	{
		char ch=x%2+'0';
		s=ch+s;
		x/=2;
	}
	
	while(s.size()<8)s='0'+s;
	
	return s;
}

string BinToInt(string s)//不要手残,循环里ans不要打成s
{
	string ans="";
	int x=(s[0]-'0')*128+(s[1]-'0')*64+(s[2]-'0')*32+(s[3]-'0')*16+(s[4]-'0')*8+(s[5]-'0')*4+(s[6]-'0')*2+(s[7]-'0');
	if(x==0)return "0";
	while(x)
	{
		char ch=x%10+'0';
		ans=ch+ans;
		x/=10;
	}
	return ans;
}

string IpToBin(int a,int b,int c,int d)//a.b.c.d -> 32位二进制数
{
	string s=""+IntTo8Bin(a)+IntTo8Bin(b)+IntTo8Bin(c)+IntTo8Bin(d);
	return s;
}

string BinToIp(string s)//32位二进制数->4个1字节十进制数
{
	string a=s.substr(0,8),b=s.substr(8,8),c=s.substr(16,8),d=s.substr(24,8);
	string ans="";
	ans=BinToInt(a)+"."+BinToInt(b)+"."+BinToInt(c)+"."+BinToInt(d);
	return ans;
}

int main()
{
	//freopen("input.in","r",stdin);
	//freopen("output.out","w",stdout);
	
	int n;
	while(cin>>n)
	{
		for(int i=1;i<=n;i++)
		{
			int a,b,c,d;
			scanf("%d.%d.%d.%d",&a,&b,&c,&d);
			IP[i]=IpToBin(a,b,c,d);
		}
		
		//掩码
		if(n==1)ans2="11111111111111111111111111111111";
		else
		{
			for(int i=0;i<32;i++)
			{
				bool flag=true;
				for(int j=2;j<=n;j++)
					if(IP[j][i]!=IP[j-1][i])
					{
						flag=false;
						break;
					}
				
				if(flag)ans2+='1';
				else
				{
					for(int j=i;j<32;j++)ans2+='0';
					break;
				}
			}
		}
		
		//网络地址
		string s=IP[1];
		for(int i=0;i<32;i++)ans1+=(ans2[i]=='1'&&s[i]=='1')+'0';
		
		cout<<BinToIp(ans1)<<endl;
		cout<<BinToIp(ans2)<<endl;
	}
	return 0;
}
2023/9/3 15:28
加载中...