1074 約瑟夫環 V2
阿新 • • 發佈:2017-08-18
style file group bsp logs n) 技術 ext quest
1074 約瑟夫環 V2
基準時間限制:1 秒 空間限制:131072 KB 分值: 160 難度:6級算法題 收藏 關註 N個人坐成一個圓環(編號為1 - N),從第1個人開始報數,數到K的人出列,後面的人重新從1開始報數。問最後剩下的人的編號。 例如:N = 3,K = 2。2號先出列,然後是1號,最後剩下的是3號。 Input2個數N和K,表示N個人,數到K出列。(2 <= N <= 10^18, 2 <= K <= 1000)
Output
最後剩下的人的編號
Input示例
3 2
Output示例
3
這題是真的卡時間啊,就差0.01秒,十多組數據都是差那麽長時間.
想了好久,憑我現在能力也優化不了我的代碼,借用一下大佬的代碼AC.
留在這以後看.
1 #include<bits/stdc++.h> //正常思路
2 using namespace std;
3 typedef long long ll;
4 #define rep(i,l,r) for(int i=l;i<=r;++i)
5 const int K=1e6+5;
6 bool b[K];
7 int k;
8 ll dfs(const ll &n){
9 if(n<=k){
10 int ans=0;
11 rep(i,2 ,n) ans=(ans+k)%i;
12 return ans;
13 }
14 ll ans=dfs(n-n/k);
15 return ( ans+n/k*k+ (ans-n%k)/(k-1) )%n;
16 }
17 int main(){
18 ll n;
19 cin>>n>>k;
20 cout<<dfs(n)+1;
21 }
22
23
24
25 //大佬說用圖像做的,具體的能看懂就自己看
26 #include<iostream>
27 #include<cstdio>
28 #include<cstring>
29 #include<algorithm>
30 using namespace std;
31 int main(){
32 unsigned long long i,j,n,k;
33 cin>>n>>k;
34 long long y=k%2;
35 long long x=2,t=0;
36 long long z1,z2;
37 z1=y;
38 z2=x;
39 while(x<=n){
40 z1=y;
41 z2=x;
42 t=(x-y)/(k-1);
43 if(t==0) t++;
44 y=y+t*k-((y+t*k)/(x+t))*(x+t);
45 x+=t;
46 }
47 cout<<(z1+(n-z2)*k)%(n)+1<<endl;
48 }
1074 約瑟夫環 V2