Hakase provides Nano with a problem. There is a rooted tree with values on nodes. For each query,you are asked to calculate the sum of the values in the subtree. However, Nano is a rookie so she decides to guess the answer. She has known how the data generator works: it identifi es the nodes with labels from 0 to n-1 and then visits them one by one. For each i (1≤i≤n), the generator selects a node whose label is smaller than i to be its father. The pseudocode is like this:
for i = 1 to n - 1:
father[i] = random(0, i - 1);
where random(a, b) randomly generates a uniformly distributed random integer in range [a, b].
Knowing n and the value of the i-th node ai , Nano decides to randomly choose a subtree and sum up all of the values in the subtree as the answer. Now Hakase wants to know what the expectation of the answer is. Can you help her?
输入
The first line contains an integer T (1≤T≤10) representing the number of test cases.
For each test case, the fi rst line contains an integer n (1≤n≤100000), the number of the nodes in the rooted tree.
The second line contains n integers a0,a1,...,an-1 (1≤ai≤100000) represent the values of nodes.
输出
It can be proven that the answer equals to an irreducible fraction p/q. For each test case, print p*q-1 mod 998244353 in one line. q-1 is the inverse of q under module number 998244353.
思路:根据点的贡献进行分析
由于由于所取模的数是质数,因此求逆元只需 qpow(n,mod-2);
# include <iostream>
# include <cstdio>
# include <cmath>
# include <algorithm>
# include<queue>
#define inf 0x3f3f3f3f
# define ll long long
#define mod 998244353
using namespace std;
ll num;
ll a,tmp;
ll qpow(ll a,ll b){
ll ans=1;
while(b){
if(b&1) ans=(ans*a)%mod;
b>>=1;
a=(a*a)%mod;
}
return ans;
}
ll inv(ll x){
return qpow(x,mod-2);
}
int main()
{
int t;
scanf("%d",&t);
while(t--){
int n;
scanf("%d",&n);
num=1;
for(int i=1;i<n;i++){
num=(num*i)%mod;
}
tmp=num;
scanf("%lld",&a);
ll ans=(num*a)%mod;
for(int i=1;i<n;i++){
scanf("%lld",&a);
tmp=tmp+num*inv(i)%mod;
ans=(ans+tmp*a)%mod;
}
num=(num*n)%mod;
printf("%lld\n",ans*inv(num)%mod);
}
return 0;
}