約瑟夫問題模板
阿新 • • 發佈:2020-08-08
1 #include<iostream> 2 #include<algorithm> 3 #include<vector> 4 #include<cstring> 5 #include<cstdio> 6 using namespace std; 7 #define mem(s,n) memset(s,n,sizeof s); 8 #define ios {ios::sync_with_stdio(false);cin.tie(0);cout.tie(0); } 9 typedef long long ll; 10 constint maxn=5e6+1; 11 const int Inf=0x7f7f7f7f; 12 ll n,k; 13 ll Josephus(ll n,ll k){ 14 if(n==1) return 0; 15 else if(n<k){ 16 ll ans=0; 17 for(int i=2;i<=n;i++) 18 ans=(ans+k)%i; 19 return ans; 20 } 21 ll ans=Josephus(n-n/k,k); 22 if(ans<n%k) ans=ans-n%k+n;23 else ans=ans-n%k+(ans-n%k)/(k-1); 24 return ans; 25 } 26 27 int main() 28 { 29 int t; 30 scanf("%d",&t); 31 while(t--) 32 { 33 scanf("%lld%lld",&n,&k); 34 // 簡便寫法; 35 ll i=1,ans=0,p; 36 while(i<n) 37 { 38 p=(i-ans)/(k-1)+((i-ans)%(k-1)!=0); 39 if(i+p>n) p=n-i; 40 ans+=p*k; 41 i+=p; 42 ans%=i; 43 } 44 // 45 cout<<Josephus(n,k)<<endl; 46 } 47 return 0; 48 }