#P3773. 第1题-智能设备监控系统
-
ID: 3116
Tried: 22
Accepted: 3
Difficulty: 3
所属公司 :
中兴
时间 :2025年9月22日
-
算法标签>数据结构模拟
第1题-智能设备监控系统
解题思路
本题要求实现一个简易的“智能设备管理系统”,支持两类设备与四种指令:
-
设备类型:Light(状态 ON/OFF)、Lock(状态 LOCKED/UNLOCKED)
-
指令:
CREATE LIGHT id initial_state
CREATE LOCK id initial_state
DISPLAY id
DISPLAY ALL
关键点与算法/数据结构选择:
-
抽象与多态:定义抽象基类
Device
,派生类Light
、Lock
分别实现状态展示方法,统一输出格式(多态的statusLine()
)。 -
查找 + 保序:
- 使用 哈希表/字典
id -> Device
实现 O(1) 查找与判重。 - 同时维护 创建顺序列表(或 Java 的
LinkedHashMap
)保证DISPLAY ALL
按创建顺序输出。
- 使用 哈希表/字典
-
指令解析与规则:
- 只有当
id
未存在且initial_state
合法时才创建;否则忽略(不输出错误信息)。 DISPLAY id
若不存在,输出Device id not found.
DISPLAY ALL
依序输出所有已创建设备的状态;若无设备,什么也不输出。
- 只有当
-
实现方法:主函数负责读入与打印;核心逻辑(设备类与处理函数)放在外部函数/类中,便于复用与测试。
代码实现
Python
from abc import ABC, abstractmethod
import sys
# 抽象设备类
class Device(ABC):
def __init__(self, did: str):
self.id = did
@abstractmethod
def status_line(self) -> str:
pass
# 智能灯
class Light(Device):
def __init__(self, did: str, state: str):
super().__init__(did)
self.state = state # "ON" / "OFF"
def status_line(self) -> str:
return f"Light {self.id} is {self.state}"
# 智能门锁
class Lock(Device):
def __init__(self, did: str, state: str):
super().__init__(did)
self.state = state # "LOCKED" / "UNLOCKED"
def status_line(self) -> str:
return f"Lock {self.id} is {self.state}"
def process_operations(lines):
"""
核心处理函数:解析指令并产生输出行
规则:非法状态/重复 id/未知指令 一律忽略
"""
devices = {} # id -> Device(字典用于 O(1) 查找)
order = [] # 记录创建顺序,供 DISPLAY ALL 使用
out = []
for raw in lines:
parts = raw.strip().split()
if not parts:
continue
if parts[0] == "CREATE" and len(parts) >= 4:
typ, did, state = parts[1], parts[2], parts[3]
if did in devices:
continue # 重复 id 忽略
if typ == "LIGHT" and state in ("ON", "OFF"):
devices[did] = Light(did, state)
order.append(did)
elif typ == "LOCK" and state in ("LOCKED", "UNLOCKED"):
devices[did] = Lock(did, state)
order.append(did)
else:
# 非法类型或状态,忽略
continue
elif parts[0] == "DISPLAY":
if len(parts) >= 2 and parts[1] == "ALL":
for did in order:
out.append(devices[did].status_line())
elif len(parts) >= 2:
did = parts[1]
if did in devices:
out.append(devices[did].status_line())
else:
out.append(f"Device {did} not found.")
# 其他 DISPLAY 形式忽略
# 其它指令忽略
return out
def main():
data = sys.stdin.read().strip().splitlines()
if not data:
return
n = int(data[0].strip())
ops = data[1:1 + n]
result = process_operations(ops)
if result:
print("\n".join(result))
if __name__ == "__main__":
main()
Java
import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.*;
// 主类
public class Main {
// 抽象设备
static abstract class Device {
String id;
Device(String id) { this.id = id; }
abstract String statusLine();
}
// 灯
static class Light extends Device {
String state; // ON / OFF
Light(String id, String state) { super(id); this.state = state; }
@Override
String statusLine() { return "Light " + id + " is " + state; }
}
// 锁
static class Lock extends Device {
String state; // LOCKED / UNLOCKED
Lock(String id, String state) { super(id); this.state = state; }
@Override
String statusLine() { return "Lock " + id + " is " + state; }
}
// 校验状态
static boolean validLight(String s) { return "ON".equals(s) || "OFF".equals(s); }
static boolean validLock(String s) { return "LOCKED".equals(s) || "UNLOCKED".equals(s); }
// 核心处理逻辑:返回所有需要打印的行
static List<String> process(List<String> lines) {
// LinkedHashMap 既能 O(1) 查找,又能保留插入顺序
Map<String, Device> map = new LinkedHashMap<>();
List<String> out = new ArrayList<>();
for (String raw : lines) {
if (raw == null) continue;
String line = raw.trim();
if (line.isEmpty()) continue;
String[] p = line.split("\\s+");
if ("CREATE".equals(p[0]) && p.length >= 4) {
String typ = p[1], id = p[2], st = p[3];
if (map.containsKey(id)) continue; // 重复 id 忽略
if ("LIGHT".equals(typ) && validLight(st)) {
map.put(id, new Light(id, st));
} else if ("LOCK".equals(typ) && validLock(st)) {
map.put(id, new Lock(id, st));
} else {
// 非法类型或状态,忽略
}
} else if ("DISPLAY".equals(p[0])) {
if (p.length >= 2 && "ALL".equals(p[1])) {
for (Device d : map.values()) out.add(d.statusLine());
} else if (p.length >= 2) {
String id = p[1];
Device d = map.get(id);
if (d != null) out.add(d.statusLine());
else out.add("Device " + id + " not found.");
}
}
}
return out;
}
public static void main(String[] args) throws Exception {
// 读入 N 与 N 行操作
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));
String s = br.readLine();
if (s == null || s.trim().isEmpty()) return;
int n = Integer.parseInt(s.trim());
List<String> ops = new ArrayList<>();
for (int i = 0; i < n; i++) {
ops.add(br.readLine());
}
List<String> ans = process(ops);
// 输出
StringBuilder sb = new StringBuilder();
for (int i = 0; i < ans.size(); i++) {
if (i > 0) sb.append('\n');
sb.append(ans.get(i));
}
System.out.print(sb.toString());
}
}
C++
#include <iostream>
#include <string>
#include <vector>
#include <unordered_map>
#include <memory>
#include <sstream>
using namespace std;
// 抽象设备
struct Device {
string id;
Device(const string& i) : id(i) {}
virtual ~Device() {}
// 统一状态字符串
virtual string statusLine() const = 0;
};
// 灯
struct Light : public Device {
string state; // "ON" / "OFF"
Light(const string& i, const string& s) : Device(i), state(s) {}
string statusLine() const override {
return "Light " + id + " is " + state;
}
};
// 锁
struct LockDev : public Device {
string state; // "LOCKED" / "UNLOCKED"
LockDev(const string& i, const string& s) : Device(i), state(s) {}
string statusLine() const override {
return "Lock " + id + " is " + state;
}
};
// 核心处理:返回所有需要输出的行
vector<string> processOperations(const vector<string>& lines) {
unordered_map<string, unique_ptr<Device>> mp; // id -> 设备
vector<string> order; // 创建顺序
vector<string> out; // 输出行
for (const string& raw : lines) {
// 使用输入流按空白分割(简洁、稳妥)
istringstream iss(raw);
vector<string> p;
string t;
while (iss >> t) p.push_back(t);
if (p.empty()) continue;
if (p[0] == "CREATE" && p.size() >= 4) {
string typ = p[1], id = p[2], st = p[3];
if (mp.count(id)) continue; // 重复 id 忽略
if (typ == "LIGHT" && (st == "ON" || st == "OFF")) {
mp[id] = unique_ptr<Device>(new Light(id, st));
order.push_back(id);
} else if (typ == "LOCK" && (st == "LOCKED" || st == "UNLOCKED")) {
mp[id] = unique_ptr<Device>(new LockDev(id, st));
order.push_back(id);
} else {
// 非法类型或状态,忽略
continue;
}
} else if (p[0] == "DISPLAY") {
if (p.size() >= 2 && p[1] == "ALL") {
for (const string& id : order) {
out.push_back(mp[id]->statusLine());
}
} else if (p.size() >= 2) {
string id = p[1];
if (mp.count(id)) out.push_back(mp[id]->statusLine());
else out.push_back("Device " + id + " not found.");
}
}
}
return out;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n;
if (!(cin >> n)) return 0;
string dummy;
getline(cin, dummy); // 读取到行尾
vector<string> ops(n);
for (int i = 0; i < n; ++i) {
getline(cin, ops[i]);
}
vector<string> ans = processOperations(ops);
for (size_t i = 0; i < ans.size(); ++i) {
if (i) cout << '\n';
cout << ans[i];
}
return 0;
}
题目内容
要求设计一个简单的智能设备监控系统。该系统能够管理不同类型的智能设备(如智能灯和智能门锁),并能统一查问它们的状态。你需要运用你所选编程语言的特性,来实现设备的抽象和具体化,以及统一的状态显示功能。
具体的实现方式应利用你所选编程语言的特性,例如:
- 对于支持面向对象编程的语言(如C++,Java,Python,C#),应设计抽象基类/接口和具体设备类,并利用多态性来统一处理设备。
对于C语言,可以考虑使用结构体和函数指针来模拟多态行为,或者通过清晰的函数命名约定来管理不同设备。
输入描述
输入包含多行,模拟对不同设备的创建和操作。
第一行包含一个整数 N(N≤100),表示操作的总次数。
接下来的 N 行,每行描述一个操作。操作类型有四种:
1、CREATE LIGHT <id><initial_state>:创建一个智能灯。<id>是字符串,<initial _state> 是 ON 或 OFF .
2、CREATE LOCK <id><initial_state>:创建一个智能门锁。<id>是字符串,<initial _state> 是 LOCKED 或 UNLOCKED .
3、DISPLAY <id> : 显示指定设备的状态。
4、DISPLAY ALL: 显示所有已创建设备的状态。
输出描述
1、对于每个 DISPLAY <id> 操作,输出对应设备的状态信息。状信格式如下:
a、智能灯:Light <id> is <ON/OFF>
b、智能门锁:Lock <id> is <LOCKED/UNLOCKED>
2、如果 DISPLAY 的 <id> 不存在,则输出 Device <id> not found.
3、对于 DISPLAY ALL 操作,按照设备创建的先后顺序,逐行输出所有设备的状态信息。
如果没有设备,则不输出任何内容。
约束与注意事项:
1、设备 ID 的唯一性: 系统中每个设备的 <id> 必须是唯一的。如果尝试使用一个已经存在的 <id> 创建新设备,则忽略该创建操作,不输出任何错误信息。
2、错误处理:
a、无效初始状态:如果 CREATE 操作提供的 <initial _state>不是 ON/OFF 或 LOCKED/UNLOCKED,则忽略该创建操作,不输出任何错误信息。
b、未知操作类型:如果输入的操作类型不是 CREATE 或 DISPLAY,也忽略该操作。
3、标准库使用:允许使用所选语言的标准库容器来管理设备,例如 C++ 的 std::map 或 std::unordered _map, Python 的 dict,Java 的 HashMap 等。
样例1
输入
7
CREATE LIGHT Light1 ON
CREATE LOCK LockA UNLOCKED
DISPLAY Light1
DISPLAY LockA
DISPLAY NonExistentDevice
DISPLAY ALL
CREATE LIGHT Light1 OFF
输出
Light Light1 is ON
Lock LockA is UNLOCKED
Device NonExistentDevice not found.
Light Light1 is ON
Lock LockA is UNLOCKED
样例2
输入
6
CREATE LIGHT LivingRoomLight OFF
CREATE LIGHT KitchenLight ON
DISPLAY KitchenLight
DISPLAY ALL
DISPLAY LivingRoomLight
CREATE LOCK MainDoor UNKNOWN_STATE
输出
Light kitchenLight is ON
Light LivingRoomLight is OFF
Light KitchenLight is ON
Light LivingRoomLight is OFF