个人评价:神题!
我们依旧先来理解题目,我们可以知道有 个角色,每个角色有操作清单、资源种类清单、资源名称清单。有 个角色关联,每个关联将角色绑定到若干用户或用户组。有 次询问,每次给出用户名、所属用户组、操作、资源种类、资源名称,以此让我们判断该用户是否能执行该操作。
思路
我们需要判断一个角色能否执行操作的条件:
- 操作清单中有该操作或
* - 资源种类清单中有该资源种类或
* - 资源名称清单为空或包含该资源名称
同时我们还需要判断用户能否执行操作:
- 找出所有与该用户关联的角色(通过用户名直接关联,或通过所属用户组关联)
- 只要有一个角色满足条件,就能执行
因为每次询问的用户组信息都是独立给出的,不能记忆之前的信息,所以必须要每次重新判断。
代码
#include <iostream>
#include <vector>
#include <string>
#include <unordered_map>
#include <unordered_set>
using namespace std;
struct Role {
unordered_set<string> ops;
unordered_set<string> resTypes;
unordered_set<string> resNames;
bool hasWildcardOp;
bool hasWildcardType;
bool hasEmptyResNames;
Role() : hasWildcardOp(false), hasWildcardType(false), hasEmptyResNames(true) {}
};
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
int n, m, q;
cin >> n >> m >> q;
unordered_map<string, Role> roles;
for (int i = 0; i < n; i++) {
string name;
cin >> name;
Role role;
int nv;
cin >> nv;
for (int j = 0; j < nv; j++) {
string op;
cin >> op;
if (op == "*") {
role.hasWildcardOp = true;
} else {
role.ops.insert(op);
}
}
int no;
cin >> no;
for (int j = 0; j < no; j++) {
string type;
cin >> type;
if (type == "*") {
role.hasWildcardType = true;
} else {
role.resTypes.insert(type);
}
}
int nn;
cin >> nn;
role.hasEmptyResNames = (nn == 0);
for (int j = 0; j < nn; j++) {
string name;
cin >> name;
role.resNames.insert(name);
}
roles[name] = role;
}
unordered_map<string, vector<string>> userToRoles;
unordered_map<string, vector<string>> groupToRoles;
for (int i = 0; i < m; i++) {
string roleName;
cin >> roleName;
int ns;
cin >> ns;
for (int j = 0; j < ns; j++) {
char type;
string name;
cin >> type >> name;
if (type == 'u') {
userToRoles[name].push_back(roleName);
} else {
groupToRoles[name].push_back(roleName);
}
}
}
for (int i = 0; i < q; i++) {
string userName;
cin >> userName;
int ng;
cin >> ng;
unordered_set<string> groups;
for (int j = 0; j < ng; j++) {
string group;
cin >> group;
groups.insert(group);
}
string operation, resourceType, resourceName;
cin >> operation >> resourceType >> resourceName;
unordered_set<string> candidateRoles;
if (userToRoles.count(userName)) {
for (const string& roleName : userToRoles[userName]) {
candidateRoles.insert(roleName);
}
}
for (const string& group : groups) {
if (groupToRoles.count(group)) {
for (const string& roleName : groupToRoles[group]) {
candidateRoles.insert(roleName);
}
}
}
bool canDo = false;
for (const string& roleName : candidateRoles) {
const Role& role = roles[roleName];
if (!role.hasWildcardOp && !role.ops.count(operation)) continue;
if (!role.hasWildcardType && !role.resTypes.count(resourceType)) continue;
if (!role.hasEmptyResNames && !role.resNames.count(resourceName)) continue;
canDo = true;
break;
}
cout << (canDo ? "1" : "0") << "\n";
}
return 0;
}