题意:一个无向树形图上每个点都有其自己的权值 c[i], 给出第 i(2<=i<=n) 个点直接相连的点 p[i],现在需要求 f(i, x)的值并分别对1e9+7和1e9+9取模输出答案。
思路:建立无向图后,每次以第 i 个点为根节点进行暴搜,得到a[i][j]的值,然后再求对应的 f(i, x)即可。暴搜时复杂度为 O(n*(n-1)),结果处理时复杂度O(n^2),题目5000的数据范围是能够通过滴。
代码实现:
#include <cstdio>
#include <cstring>
#include <cmath>
#include <cstdlib>
#include <ctime>
#include <cctype>
#include <cstring>
#include <iostream>
#include <sstream>
#include <string>
#include <list>
#include <vector>
#include <set>
#include <map>
#include <queue>
#include <stack>
#include <algorithm>
#include <functional>
#define endl '\n'
#define null NULL
#define ll long long
#define int long long
#define pii pair<int, int>
#define lowbit(x) (x &(-x))
#define ls(x) x<<1
#define rs(x) (x<<1+1)
#define me(ar) memset(ar, 0, sizeof ar)
#define mem(ar,num) memset(ar, num, sizeof ar)
#define rp(i, n) for(int i = 0, i < n; i ++)
#define rep(i, a, n) for(int i = a; i <= n; i ++)
#define pre(i, n, a) for(int i = n; i >= a; i --)
#define IOS ios::sync_with_stdio(0); cin.tie(0);cout.tie(0);
const int way[4][2] = {{1, 0}, {-1, 0}, {0, 1}, {0, -1}};
using namespace std;
const int inf = 0x3f3f3f3f3f3f3f3f;
const double PI = acos(-1.0);
const double eps = 1e-6;
const int mod1 = 1e9 + 7, mod2 = 1e9 + 9;
const int N = 2e3 + 5;
int T = 1, n, c[N], y = 19560929;
int a[N][N];
bool vis[N];
vector<int> g[N];
void dfs(int fa, int u, int cnt) {
if(a[fa][u]) return;
a[fa][u] = cnt;
for(auto v:g[u]) {
if(a[fa][v]) continue;
if(vis[c[v]]) dfs(fa, v, cnt);
else {
vis[c[v]] = 1;
dfs(fa, v, cnt + 1);
vis[c[v]] = 0; //回溯
}
}
}
signed main() {
cin >> T;
while(T --){
cin >> n;
for(int i = 1; i <= n; i ++)
for(int j = 1; j <= n; j ++)
a[i][j] = 0;
for(int i = 1; i <= n; i ++) g[i].clear();
for(int i = 2; i <= n; i ++){
int x; cin >> x;
g[x].push_back(i);
g[i].push_back(x);
}
for(int i = 1; i <= n; i ++) cin >> c[i];
for(int i = 1; i <= n; i ++) {
vis[c[i]] = 1;
dfs(i, i, 1);
vis[c[i]] = 0; //恢复节点状态
int ans1 = 0, ans2 = 0, x1 = 1, x2 = 1;
for(int j = 1; j <= n; j ++){
ans1 = (ans1+a[i][j]*x1%mod1)%mod1;
ans2 = (ans2+a[i][j]*x2%mod2)%mod2;
x1 = (x1*y)%mod1;
x2 = (x2*y)%mod2;
}
cout << ans1 << " " << ans2 << endl;
}
}
return 0;
}