- 一颗二叉树,节点是1-n,根节点是1,其他节点的顺序未知
每个节点可能是红色或蓝色
每个节点的权重=根到该节点的路径上两色之差,取绝对值
求所有节点的权重和
输入路径,但不知父子关系,如:
12
24
31
我当时的答案,但是只过了30%
#include <iostream>
#include <vector>
#include <string>
#include <queue>
using namespace std;
using vi = vector<int>;
int main() {
int n;
int res = 0;
cin >> n;
string colors;
cin >> colors;
colors = '0' + colors;
vector<vi> tree(n + 1);
vi weight(n + 1);
/**
* 0 not visited
* 1 red is more
* 2 equal
* 3 blue is more
*/
vi visited(n + 1);
for (int i = 1; i < n; i++) {
int a, b;
cin >> a >> b;
tree[a].emplace_back(b);
tree[b].emplace_back(a);
}
queue<int> q;
q.push(1);
if (colors[1] == 'R') {
weight[1] = 1;
visited[1] = 1;
} else {
weight[1] = -1;
visited[1] = 3;
}
// weight[1] = colors[1] == 'R' ? 1 : -1;
// visited[1] = 1;
res = weight[1];
while (!q.empty()) {
int curr_node = q.front();
// res += weight[curr_node];
q.pop();
for (int i = 0; i < tree[curr_node].size(); i++) {
int son = tree[curr_node][i];
if (visited[son]) continue;
visited[son] = 1;
if (colors[son] == 'R') {
if (visited[curr_node] < 3) {
weight[son] = weight[curr_node] + 1;
visited[son] = 1;
} else {
weight[son] = weight[curr_node] - 1;
if (weight[son] == 0) {
visited[son] = 2;
} else {
visited[son] = 3;
}
}
} else {
if (visited[curr_node] == 1) {
weight[son] = weight[curr_node] - 1;
if (weight[son] == 0) {
visited[son] = 2;
} else {
visited[son] = 1;
}
} else {
weight[son] = weight[curr_node] + 1;
visited[son] = 3;
}
}
// cout << son << " " << weight[son] << endl;
res += weight[son];
q.push(son);
// for (int j = 0; j < tree[son].size(); j++) {
// int grandson = tree[son][j];
// if (visited[grandson] == 0) {
// q.push(grandson);
// }
// }
}
}
cout << res;
return 0;
}
- 输入如下格式
1 Alice 2
Zoom Apple
2 Bob
2 Alice
1 Bob 2
Apple Microsoft
2 Bob
1开头表示这是一个注册请求,占2行
2表示这是一个查询请求,占1行
要实现一个推荐系统,所有相关联的项目会组成一个集合,与之相关的人要收到推荐
如开头表示:Alice关注2个,zoom和apple
查询bob,不存在
查询Alice,推荐个数0
注册bob,关注2个,apple Microsoft
这一动作组成了推荐集合【zoom,apple,Microsoft】
查询bob,推荐1个,zoom
对于每个2请求,返回推荐的个数,注意关联集合有传递性