红栗编程社区

 找回密码
 立即注册
查看: 618|回复: 0

题解:网络连接(network)

[复制链接]

9

主题

11

帖子

136

积分

版主

Rank: 7Rank: 7Rank: 7

积分
136
发表于 2022-10-23 11:14:33 | 显示全部楼层 |阅读模式
网络连接(network)

#include<iostream>                                                                        
#include<string>                                                                              
using namespace std;                                                               
int n,k;//k计数,合法服务机的数量
struct f{
    int id;string ad;//id是编号
}a[1010];
bool check(string s){//检查地址是否合法
    int len=s.size();
    if(len>21)return false;
    string r="";
    int t=0;//统计当前是第几个数字
    string w="";//分解数字
    for(int i=0;i<=len-1;i++){
        if(s>='0'&&s<='9'){
            w=w+s;
            if(i==len-1 || !(s[i+1]>='0'&&s[i+1]<='9')){
                t++;//一个新数字
                if(t>5) return false;
                if(w.size()>5) return false;
                if(w[0]=='0' &&w!="0") return false;//前导0
                 
                int x=stoi(w);//字符串变数字
                if(t<=4&&x>255) return false;
                if(t==5&&x>65535) return false;
                w="";
                r=r+"0";
            }
        }else{
            r=r+s;//0.0.0.0:0
        }
    }
    if(r!="0.0.0.0:0") return false;
    return true;
}
bool server(string ad){
    for(int i=1;i<=k;i++){
        if(ad==a.ad) return false;//地址重复
    }
    return true;
}
int client(string ad){
    for(int i=1;i<=k;i++){
        if(ad==a.ad) return a.id;//能够连接服务器,返回编号
    }
    return 0;
}                                                                                   
int main(){                           
    cin>>n;                                    
    for(int i=1;i<=n;i++){                             
        string op,ad;
        cin>>op>>ad;
        if(!check(ad)){
            cout<<"ERR"<<endl;continue;
        }
        if(op=="Server"){//地址和法,而且是服务机
            if(server(ad)){//服务机OK
                cout<<"OK"<<endl;
                a[++k].id=i;a[k].ad=ad;//存储回复的服务机地址
            }else{//服务机FAIL: 服务机地址重复
                cout<<"FAIL"<<endl;
            }
        }else{//地址和法,而且是客户机
            int pos=client(ad);
            if(pos){
                cout<<pos<<endl;
            }else{
                cout<<"FAIL"<<endl;
            }
        }                    
    }            
    return 0;                        
}      

回复

使用道具 举报

您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

Archiver|手机版|小黑屋|红栗编程首页 ( 湘ICP备19013686号-4 )

GMT+8, 2024-6-2 04:05 , Processed in 0.039440 second(s), 22 queries .

论坛主要用于编程经验和问题的学习交流,禁止发布任何与学习无关的信息,违者删帖、封号。

Copyright © 2019-2022.

快速回复 返回顶部 返回列表