链接:https://ac.nowcoder.com/acm/contest/624/J
来源:牛客网
题目描述
Do you know bubble sort algorithm? It’s one of the most famous sorting algorithms.
The bubble sort algorithm is stable, which can be described below:
It’s easy for us to find that we need swap (n−1)⋅(n−2)⋯2⋅1 times in the worst case, so the total swapping count is about O(n^2) where n is the length of the given sequence.
But the above result is an approximate result. As a curious student, Ramen is wondering, among all permutations of length n, what the value of the average exact swap count is?
输入描述:
The input contains multiple test cases.
The first line is an integer T(1 <= T <= 10000), which indicates represents the number of test cases.
Each of the next T lines contains an integer n(1 <= n <= 1e18), represents the length of the permutation.
输出描述:
For each test case, output the average swap count in one single line.
To avoid possible errors, if the answer is
P/Q you need to output P*Q^-1 mod 998244353
Q^−1 is the minimum number that suits
Q⋅Q^−1≡1(mod998244353)
示例1
输入
3
1
3
1000000000000000000
输出
0
499122178
178803651
解题思路:
化简一下求和式子得到ans=n * (n-1)/4, 用exgcd 算4 mod 998244353 的逆元
代码:
#include<bits/stdc++.h>
using namespace std;
typedef long long LL;
inline LL read(){
LL x=0,f=0;char ch=getchar();
while(ch>'9'||ch<'0')f|=ch=='-',ch=getchar();
while(ch>='0'&&ch<='9')x=(x<<3)+(x<<1)+(ch^48),ch=getchar();
return f?-x:x;
}
const LL mod=998244353;
void extgcd(LL a,LL b,LL& d,LL& x,LL& y){
if(!b){d=a,x=1,y=0;}
else{extgcd(b,a%b,d,y,x);y-=x*(a/b);}
}
LL inverse(LL a,LL n){
LL d,x,y;
extgcd(a,n,d,x,y);
return d==1?(x+n)%n:-1;
}
int main(){
int t=read();
LL tp=inverse(4,mod);
while(t--){
LL n=read();
LL ans=((n%mod)*((n-1)%mod))%mod*tp%mod;
printf("%lld\n",ans);
}
}