本题链接:202104-3 DHCP服务器
本博客给出本题截图:
C++
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
const int N = 10010;
int n, m, t_def, t_max, t_min;
string h;
struct IP
{
int state;
int t;
string owner;
}ip[N];
void update_ips_state(int tc)
{
for (int i = 1; i <= n; i ++ )
if (ip[i].t && ip[i].t <= tc)
{
if (ip[i].state == 1)
{
ip[i].state = 0;
ip[i].owner = "";
ip[i].t = 0;
}
else
{
ip[i].state = 3;
ip[i].t = 0;
}
}
}
int get_ip_by_owner(string client)
{
for (int i = 1; i <= n; i ++ )
if (ip[i].owner == client)
return i;
return 0;
}
int get_ip_by_state(int state)
{
for (int i = 1; i <= n; i ++ )
if (ip[i].state == state)
return i;
return 0;
}
int main()
{
cin >> n >> t_def >> t_max >> t_min >> h;
cin >> m;
while (m -- )
{
int tc;
string client, server, type;
int id, te;
cin >> tc >> client >> server >> type >> id >> te;
if (server != h && server != "*")
{
if (type != "REQ") continue;
}
if (type != "DIS" && type != "REQ") continue;
if (server == "*" && type != "DIS" || server == h && type == "DIS") continue;
update_ips_state(tc);
if (type == "DIS")
{
int k = get_ip_by_owner(client);
if (!k) k = get_ip_by_state(0);
if (!k) k = get_ip_by_state(3);
if (!k) continue;
ip[k].state = 1, ip[k].owner = client;
if (!te) ip[k].t = tc + t_def;
else
{
int t = te - tc;
t = max(t, t_min), t = min(t, t_max);
ip[k].t = tc + t;
}
cout << h << ' ' << client << ' ' << "OFR" << ' ' << k << ' ' << ip[k].t << endl;
}
else
{
if (server != h)
{
for (int i = 1; i <= n; i ++ )
if (ip[i].owner == client && ip[i].state == 1)
{
ip[i].state = 0;
ip[i].owner = "";
ip[i].t = 0;
}
continue;
}
if (!(id >= 1 && id <= n && ip[id].owner == client))
cout << h << ' ' << client << ' ' << "NAK" << ' ' << id << ' ' << 0 << endl;
else
{
ip[id].state = 2;
if (!te) ip[id].t = tc + t_def;
else
{
int t = te - tc;
t = max(t, t_min), t = min(t, t_max);
ip[id].t = tc + t;
}
cout << h << ' ' << client << ' ' << "ACK" << ' ' << id << ' ' << ip[id].t << endl;
}
}
}
return 0;
}
总结
大模拟题,近几年csp认证考试中比较简单的一道模拟题
阅读理解 + 细致
适当的备注可以减少我们后期写代码时的混乱
逐行翻译内容,按照要求写代码