#include<bits/stdc++.h>
#define LL long long
#define INF INT64_MAX
#define MOD 998244353
#define ls rt << 1
#define rs rt << 1 | 1
using namespace std;
typedef pair<int,int>pa;
const int N = 100005;
const int b = 19560929;
vector<int> v[2005];
int c[2005], cnt[2005];
LL a[2005], p1[2005], p2[2005], ans;
void dfs(int x, int from){
//printf("x = %d\n", x);
if(!cnt[c[x]]) ans++;
a[x] = ans;
cnt[c[x]]++;
for(auto it: v[x])
if(it!=from) dfs(it, x);
if(cnt[c[x]]==1) ans--;
cnt[c[x]]--;
}
int main(){
int t, n, x;
scanf("%d", &t);
p1[0]=p2[0]=1;
for(int i = 1;i <= 2001;i++){
p1[i]=p1[i-1]*b%MOD;
p2[i]=p2[i-1]*b%MOD2;
}
while(t--){
scanf("%d", &n);
for(int i = 2;i <= n;i++){
scanf("%d", &x);
v[x].push_back(i);v[i].push_back(x);
}
for(int i = 1;i <= n;i++) scanf("%d", &c[i]);
for(int i = 1;i <= n;i++){
dfs(i, -1);
LL ans1=0, ans2=0;
for(int j = 1;j <= n;j++){
ans1 += a[j]*(LL)p1[j-1]%MOD;
if(ans1>=MOD) ans1-=MOD;
//printf("%lld, a[%d]=%lld\n", ans1,j, a[j]);
ans2 += a[j]*p2[j-1]%MOD2;
if(ans2>=MOD2) ans2-=MOD2;
}
printf("%lld %lld\n", ans1, ans2);
}
for(int i = 1;i <= n;i++) v[i].clear();
}
return 0;
}
hud6986 Kanade Loves Maze Designing 简单dfs
最新推荐文章于 2025-12-31 21:25:26 发布
这段代码实现了一个基于深度优先搜索(DFS)的算法,用于计算图中每个节点的贡献值的模逆幂。程序首先初始化一些常数,如最大整数、模数等,然后通过DFS遍历图中的节点,更新节点的贡献值并计算最终的答案。在每一步中,它会更新节点的贡献次数,并根据贡献次数调整答案。最后,程序会输出两个答案,分别对应于模逆幂的不同计算方式。该程序可能用于图论或组合数学问题的求解。

2万+

被折叠的 条评论
为什么被折叠?



