洛谷P7911 [CSP-J 2021] 网络连接题解

普通的模拟题,数据很小,基本排除超时超空间的可能

上代码:

cpp 复制代码
#include<bits/stdc++.h>
#define LL long long
using namespace std;
vector<pair<int,string>>sv;//用于存储Server,sv[i].first代表Server编号, sv[i].second代表Server地址 
int turn(string str){//string转int 
	if(str.size()>5||str.size()==0)return -1;
	if(str.size()>1&&str[0]=='0')return -1;
	int v=1,sum=0;
	stack<int>num;//存储每一位数 
	for(int c:str){//入栈 
		num.push(c-'0');
	}
	while(!num.empty()){//遍历 
		int w=num.top();
		num.pop();
		sum+=w*v;//当前数乘权值 
		v*=10;
	}
	return sum;
}
bool check(string str){
	string s[10];
	int cnt=1,cnt1=0,cnt2=0;//cnt为地址分段数(即将ip以'.'或':'为间隔分成cnt段) ,cnt1为'.'数量, cnt2为':'数量 
	for(int i=0;i<str.size();i++){
		if(str[i]=='.'){
			if(cnt2)return 0;//若前方出现过':' ,返回0 
			cnt1++;
			cnt++;
		}else if(str[i]==':'){
			if(cnt1!=3)return 0;//若前方没有3个'.' ,返回0 
			cnt2++;
			cnt++;
		}else s[cnt]+=str[i];
		
	}
	if(cnt!=5)return 0;//若地址数量不等于五 
	if(cnt1!=3||cnt2!=1)return 0;//若'.'数量不为三或':'数量不为1 
	for(int i=1;i<cnt;i++){
		int num=turn(s[i]);
		if(!(0<=num&&num<=255))return 0;
		if(num==-1)return 0;
	}
	if(!(0<=turn(s[5])&&turn(s[5])<=65535))return 0;
	return 1;
}
int find(string str){//在Servers中寻找地址为str的Server 
	for(pair<int,string> w:sv){
		if(w.second==str){//找到地址 
			return w.first;//返回下标 
		}
	}
	return 0;//不存在,返回特殊值0(地址从1开始) 
}
int main(){
	int n;
	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(find(ad)){//巧妙利用整数转布尔值非0值为1的特性 
				cout<<"FAIL"<<endl;//服务器存在,连接失败 
			}else{
				cout<<"OK"<<endl;
				sv.push_back({i,ad});//服务器连接成功
			}
		}else{
			int get=find(ad);//sv中地址为ad的Server的数量 
			if(get){//若该Server存在 
				cout<<get<<endl;
			}else cout<<"FAIL"<<endl;//连接失败 
		}
	}

	return 0;
}

原题链接

相关推荐
梁辰兴20 小时前
计算机网络基础:超文本传输协议 HTTP
网络协议·计算机网络·http·计算机·超文本传输协议·计算机网络基础·梁辰兴
pie_thn2 天前
小容量32单片机也上bootloader?拆机烧录的苦谁懂,能上抓紧上
嵌入式·编程
乐茵lin2 天前
github开源项目 “校园活动平台“ —— 报名活动二维码生成核销流程详解
计算机·微服务·golang·开源·github·大学生·zero
程序员鱼皮3 天前
40 个 Agent Skills 精选资源:入门教程 + 实用工具 + 必装推荐
前端·后端·计算机·ai·程序员·互联网·编程
良许Linux3 天前
嵌入式处理器架构
stm32·单片机·程序员·嵌入式·编程
梁辰兴3 天前
计算机网络基础:远程终端协议 Telnet
网络·计算机网络·计算机·telnet·计算机网络基础·梁辰兴·远程终端协议
BHXDML4 天前
线上事故发生时,你第一反应是什么?
linux·运维·服务器·计算机
爱思德学术4 天前
中国计算机学会(CCF)推荐学术会议-B(软件工程/系统软件/程序设计语言):ICFP 2026
编程
程序员鱼皮5 天前
全网最简单的 OpenClaw 部署教程,5 分钟拥有你的 AI 员工
计算机·ai·程序员·互联网·网站
梁辰兴5 天前
计算机网络基础:域名系统 DNS
网络·计算机网络·计算机·dns·域名系统·计算机网络基础·梁辰兴