简答题
偏难
#22114
网络连接
网络连接

答案与解析
正确答案:<pre class="brush:cpp;toolbar:false">#include <bits/stdc++.h>
using namespace std;
map<string, int> vis;
int n;
bool check(char s[]) {
int a = -1, b = -1, c = -1, d = -1, e = -1;
// 尝试读入,保存至变量中
int t = sscanf(s, "%d.%d.%d.%d:%d", &a, &b, &c, &d, &e);
// 必须读入5个部分才可能合法
if (t != 5) return 0;
// 检查各部分数值范围
if (a < 0 || a > 255) return 0;
if (b < 0 || b > 255) return 0;
if (c < 0 || c > 255) return 0;
if (d < 0 || d > 255) return 0;
if (e < 0 || e > 65535) return 0;
// 格式化后与原字符串对比,确保无冗余格式
char s2[35];
sprintf(s2, "%d.%d.%d.%d:%d", a, b, c, d, e);
int lens = strlen(s);
for (int i = 0; i < lens; i++) {
if (s[i] != s2[i]) {
return 0;
}
}
return 1;
}
int main() {
// freopen("network.in","r",stdin);
// freopen("network.out","w",stdout);
cin >> n;
for (int i = 1; i <= n; i++) {
char op[1005], ad[1005];
cin >> op >> ad;
string t(ad);
if (op[0] == 'S') { // 服务机操作
if (!check(ad)) {
cout << "ERR" << endl; // 地址不合法
} else if (vis.count(t) != 0) {
cout << "FAIL" << endl; // 已存在该服务机
} else {
cout << "OK" << endl; // 注册成功
vis[t] = i; // 记录编号
}
} else { // 客户机操作
if (!check(ad)) {
cout << "ERR" << endl; // 地址不合法
} else if (vis.count(t) == 0) {
cout << "FAIL" << endl; // 找不到对应服务机
} else {
cout << vis[ad] << endl; // 输出对应服务机编号
}
}
}
return 0;
}</pre><p><br/></p>
这道题暂未补解析。