1342E - Placing Rooks - CodeForces Solution


combinatorics fft math *2300

Please click on ads to support us..

C++ Code:

#include<bits/stdc++.h>
using ll=long long;
const ll mod=998244353;
ll mod_pow(ll a,ll n,ll mod)
{
	ll ans=1;
	a%=mod;
	while(n)
	{
		if(n&1)ans=(ans*a)%mod;
		a=(a*a)%mod;
		n>>=1;
	}
	return ans%mod;
}
ll mod_mul(ll a,ll b,ll mod)
{
	a%=mod;
	b%=mod;
	ll ans=0;
	while(b)
	{
		if(b&1)ans=(ans+a)%mod;
		a=(a+a)%mod;
		b>>=1;
	}
	return ans%mod;
}
ll gcd(ll a,ll b)
{
	if(!b)return a;
	else return gcd(b,a%b);
}
ll exgcd(ll a,ll b,ll&x,ll&y)
{
	if(!b){x=1;y=0;return a;}
	else
	{
		ll d=exgcd(b,a%b,y,x);
		y-=(a/b)*x;
		return d;
	}
}
ll mod_inv(ll a,ll mod)
{
	ll x,y;
	exgcd(a,mod,x,y);
	return (x%mod+mod)%mod;
}
const int maxn=1e6+1e1;
ll f[maxn]{},inv_f[maxn]{};
void fact_init(int n,ll mod)
{
	f[0]=1;
	for(int i=1;i<=n;i++)
	{
		f[i]=f[i-1]*i%mod;
	}
	inv_f[n]=mod_inv(f[n],mod);
	for(int i=n-1;i>=0;i--)
	{
		inv_f[i]=inv_f[i+1]*(i+1)%mod;
	}
}
ll C(ll n,ll m)
{
	if(n<m)return 0;
	else 
	{
		ll ans=f[n];
		ans=mod_mul(ans,inv_f[m],mod);
		ans=mod_mul(ans,inv_f[n-m],mod);
		return ans;
	}
}
ll add(ll x,ll y)
{
	return (x+y)%mod;
}
ll sub(ll x,ll y)
{
	return add(x,mod-y);
}
void solve()
{
	ll n,k;std::cin>>n>>k;
	if(k>n-1)
	{
		std::cout<<0<<"\n";
		return;
	}
	fact_init(n,mod);
//	for(int i=1;i<=n;i++){std::cout<<f[i]<<" ";}std::cout<<"\n";
//	for(int i=1;i<=n;i++){std::cout<<inv_f[i]<<" ";}std::cout<<"\n";
	ll ans=0;
	ll c=n-k;
	for(ll i=c;i>=0;i--)
	{
		if(i%2==c%2)
		{
			ans=add(ans,mod_mul(mod_pow(i,n,mod),C(c,i),mod));
//			std::cout<<ans<<"\n";
		}
		else
		{
			ans=sub(ans,mod_mul(mod_pow(i,n,mod),C(c,i),mod));
//			std::cout<<ans<<"\n";
		}
	}
	ans=mod_mul(ans,C(n,c),mod);
//	std::cout<<ans<<"\n";
	if(k>0)ans=mod_mul(ans,2,mod);
	std::cout<<ans<<"\n";
}
int main()
{
	std::cin.tie(nullptr)->sync_with_stdio(false);
	solve();
	return 0;
}


Comments

Submit
0 Comments
More Questions

1245C - Constanze's Machine
1005A - Tanya and Stairways
1663F - In Every Generation
1108B - Divisors of Two Integers
1175A - From Hero to Zero
1141A - Game 23
1401B - Ternary Sequence
598A - Tricky Sum
519A - A and B and Chess
725B - Food on the Plane
154B - Colliders
127B - Canvas Frames
107B - Basketball Team
245A - System Administrator
698A - Vacations
1216B - Shooting
368B - Sereja and Suffixes
1665C - Tree Infection
1665D - GCD Guess
29A - Spit Problem
1097B - Petr and a Combination Lock
92A - Chips
1665B - Array Cloning Technique
1665A - GCD vs LCM
118D - Caesar's Legions
1598A - Computer Game
1605A - AM Deviation
1461A - String Generation
1585B - Array Eversion
1661C - Water the Trees