题解:P14436 [JOISC 2013] 间谍 / Spy
P14436 [JOISC 2013] 间谍 / Spy
题目传送门
思路
- 员工参与项目的范围是负责人及其所有下属(即以负责人为根的子树)。因此,
i_a 参与s_b 等价于s_b 的负责人是i_a 的祖先(含自身);j_a 参与r_b 等价于r_b 的负责人是j_a 的祖先。 - 对每个项目
b ,若R_b 是j_a 的祖先且S_b 是i_a 的祖先,则i_a 在该项目中成功。
步骤:
- 记录研究项目负责人为
j_R 且间谍项目负责人为i_S 的项目总数。 - 对每个
R 和员工i_y ,利用树的父节点关系递推。 - 对每个
i_a ,遍历j_a 的所有祖先R ,累加即可。
到这应该都会写了。
时间复杂度为
空间复杂度为
#include<bits/stdc++.h>
using namespace std;
constexpr int N = 7891;
int a[N], b[N], c[N][N], d[N], e[N], sum[N][N], cnt[N][N], ans[N], n, m;
int main(){
cin >> n >> m;
for(int i = 1; i <= n; i++) cin >> a[i] >> b[i];
for(int i = 1; i <= m; i++){
int x, y;
cin >> x >> y;
cnt[x][y]++;
}
int minn = -1;
for(int i = 1; i <= n; i++){
if(b[i] == 0){
minn = i;
}else{
int temp = b[i];
c[temp][d[temp]++] = i;
}
}
int num = 0;
queue<int> q;
q.push(minn);
while(!q.empty()){
int u = q.front();
q.pop();
e[num++] = u;
for(int i = 0; i < d[u]; i++){
int v = c[u][i];
q.push(v);
}
}
for(int i = 1; i <= n; i++){
for(int j = 0; j < num; j++){
int y = e[j];
if(b[y] == 0){
sum[i][y] = cnt[i][y];
}else{
sum[i][y] = cnt[i][y] + sum[i][b[y]];
}
}
}
for(int i = 1; i <= n; i++){
int temp = i, total = 0;
while(temp != 0){
total += sum[temp][i];
temp = a[temp];
}
ans[i] = total;
}
for (int i = 1; i <= n; i++) cout << ans[i] << '\n';
return 0;
}