哈尔滨工业大学(威海)第九届ACM程序设计竞赛 J逆元

链接: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);
	}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值