#include<bits/stdc++.h>
using namespace std;
#define pb push_back
#define all(x) x.begin(), x.end()
typedef long long ll;
typedef pair<int, int> PII;
const int N = 5e5 + 10, mod = 1e9 + 7, INF = 0x3f3f3f3f;
ll fact[N], infact[N];
ll qmi(ll a, ll b) {
ll res = 1;
while (b) {
if (b & 1) res = res * a % mod;
a = a * a % mod;
b >>= 1;
}
return res;
}
ll c(int a, int b) {
if (a < b) return 0;
return fact[a] * infact[b] % mod * infact[a - b] % mod;
}
void solve() {
int n;
cin >> n;
vector<ll> a(n), b(n), w(n);
for (int i = 0; i < n; i++) cin >> a[i];
for (int i = 0; i < n; i++) cin >> b[i], b[i]--;
for (int i = 0; i < n; i++) cin >> w[i];
vector<int> g(n, -1), rd(n), tp, cir(n, 1), dep(n), f(n);
vector<ll> ans(n);
for (int i = 0; i < n; i++) {
if (a[i] < a[b[i]]) ans[i] = a[i] + w[i], f[i] = 1;
else if (a[i] >= a[b[i]] + w[b[i]]) ans[i] = a[i];
else {
g[i] = b[i];
rd[b[i]]++;
}
}
for (int i = 0; i < n; i++) {
if (!rd[i]) tp.pb(i);
}
for (int i = 0; i < tp.size(); i++) {
int u = tp[i];
cir[u] = 0;
int v = g[u];
if (v == -1) continue;
rd[v]--;
if (!rd[v]) tp.pb(v);
}
for (int i = 0; i < n; i++)
if (cir[i]) ans[i] = a[i];
for (int i = tp.size() - 1; i >= 0; i--) {
int u = tp[i];
int v = g[u];
if (v == -1) {
dep[u] = 1;
} else if (cir[v]) {
cir[u] = 1;
ans[u] = a[u];
} else if (f[v]) {
dep[u] = dep[v] + 1;
ans[u] = a[u] + w[u] * c(n, dep[u]) % mod * fact[n - dep[u]] % mod * infact[n] % mod;
f[u] = 1;
} else {
ans[u] = a[u];
}
}
for (auto x : ans) cout << x % mod << " ";
cout << "\n";
}
int main() {
ios::sync_with_stdio(false), cin.tie(nullptr), cout.tie(nullptr);
int tt = 1;
cin >> tt;
fact[0] = infact[0] = 1;
for (int i = 1; i <= 500000; i ++ ) {
fact[i] = fact[i - 1] * i % mod;
infact[i] = infact[i - 1] * qmi(i, mod - 2) % mod;
}
while(tt--) {
solve();
}
return 0;
}
2023icpc杭州站 H题
最新推荐文章于 2024-05-17 12:22:02 发布