1、染色树计算权重
给定一棵树,树上每个节点红或黑。根为1,每个节点的权重值为根节点到该节点路径上红色节点个数和蓝色节点个数的差的绝对值。求所有节点权重值之和。
思路:临接矩阵+dfs
// 染色图
// 临接矩阵 dfs
long long sum = 0;
// dfs
void dfsCalculateRoute(const vector<vector<int>>& picture, const string& colour, vector<bool> visitor, pair<int,int> nowclour, int index) {
int n = (int)colour.size();
visitor[index] = true;
if (colour[index] == 'R') {
nowclour.first++;
} else {
nowclour.second++;
}
sum += abs(nowclour.first - nowclour.second);
for (int i=0; i<n; i++) {
if (picture[index][i] == 1 && !visitor[i]) {
dfsCalculateRoute(picture, colour, visitor, nowclour, i);
}
}
}
// 遍历
long long calculateRouteLength(vector<vector<int>>& picture, string& colour) {
int n = (int)colour.size();
vector<bool> visitor(n, false);
dfsCalculateRoute(picture, colour, visitor, {0,0}, 0);
return sum;
}
2、股票推荐
股票推荐系统设计,两种操作:
(1)更新用户,包含用户名+用户关注的股票列表
(2)查找用户推荐股票,根据用户名查找给该用户推荐的股票。推荐规则是和用户当前关注股票有关联性(其他用户同时关注过)
思路:哈希并查集
// 股票推荐
// 并查集,双map
class StockSystem {
public:
void registerAccount(string name, vector<string> company) {
if (account_map.find(name) != account_map.end()) {
return;
}
set<string> tmp;
for (string &x: company) {
tmp.insert(x);
if (company_map.find(x) == company_map.end()) {
company_map[x] = x;
}
}
string root = findFather(company[0]);
for (string &x: company) {
if (findFather(x)!=root) {
company_map[findFather(x)] = root;
}
}
account_map[name] = tmp;
}
int findAccount(string name) {
// 没人
int res = 0;
if (account_map.find(name) == account_map.end()) {
return -1;
}
set<string> company_set = account_map[name];
string symbol_name = *company_set.begin();
for (auto item = company_map.begin(); item!=company_map.end(); item++) {
if (company_set.find(item->first) == company_set.end() &&
findFather(symbol_name) == findFather(item->first)) {
res++;
}
}
return res;
}
private:
string findFather(string name) {
if (name == company_map[name]) {
return name;
}
return findFather(company_map[name]);
}
map<string, string> company_map;
map<string, set<string>> account_map;
};
// 写死证明一下
void hardCodeTest() {
StockSystem system;
system.registerAccount("Alice", {"A", "B"});
cout << system.findAccount("Bob") << endl;
cout << system.findAccount("Alice") << endl;
system.registerAccount("Bob", {"C", "D"});
cout << system.findAccount("Bob") << endl;
cout << system.findAccount("Alice") << endl;
system.registerAccount("Bobby", {"A", "B", "C", "D"});
cout << system.findAccount("Bob") << endl;
cout << system.findAccount("Alice") << endl;
}