BZOJ 1965 洗牌(扩展欧几里得)

时间:2023-03-10 07:15:53
BZOJ 1965 洗牌(扩展欧几里得)

容易发现,对于牌堆里第x张牌,在一次洗牌后会变成2*x%(n+1)的位置。

于是问题就变成了求x*2^m%(n+1)=L,x在[1,n]范围内的解。

显然可以用扩展欧几里得求出。

# include <cstdio>
# include <cstring>
# include <cstdlib>
# include <iostream>
# include <vector>
# include <queue>
# include <stack>
# include <map>
# include <bitset>
# include <set>
# include <cmath>
# include <algorithm>
using namespace std;
# define lowbit(x) ((x)&(-x))
# define pi acos(-1.0)
# define eps 1e-
# define MOD
# define INF
# define mem(a,b) memset(a,b,sizeof(a))
# define FOR(i,a,n) for(int i=a; i<=n; ++i)
# define FO(i,a,n) for(int i=a; i<n; ++i)
# define bug puts("H");
# define lch p<<,l,mid
# define rch p<<|,mid+,r
# define mp make_pair
# define pb push_back
typedef pair<int,int> PII;
typedef vector<int> VI;
# pragma comment(linker, "/STACK:1024000000,1024000000")
typedef long long LL;
int Scan() {
int x=,f=;char ch=getchar();
while(ch<''||ch>''){if(ch=='-')f=-;ch=getchar();}
while(ch>=''&&ch<=''){x=x*+ch-'';ch=getchar();}
return x*f;
}
const int N=;
//Code begin... LL mult_mod(LL a, LL b, LL c){
a%=c; b%=c;
LL ret=, tmp=a;
while (b){
if (b&) {
ret+=tmp;
if (ret>c) ret-=c;
}
tmp<<=;
if (tmp>c) tmp-=c;
b>>=;
}
return ret;
}
LL pow_mod(LL a, LL n, LL mod){
LL ret=, temp=a%mod;
while (n) {
if (n&) ret=mult_mod(ret,temp,mod);
temp=mult_mod(temp,temp,mod);
n>>=;
}
return ret;
}
LL extend_gcd(LL a, LL b, LL &x, LL &y){
if (a==&&b==) return -;
if (b==) {x=; y=; return a;}
LL d=extend_gcd(b,a%b,y,x);
y-=a/b*x;
return d;
}
int main ()
{
LL n, m, l, a, b, d, x, y, mod;
scanf("%lld%lld%lld",&n,&m,&l);
a=pow_mod(,m,n+); b=n+;
d=extend_gcd(a,b,x,y); x=x*l/d; mod=b/d;
x=(x%mod+mod)%mod;
printf("%lld\n",x);
return ;
}