ACM-ICPC 2018 沈阳赛区现场赛 K. Let the Flames Begin (约瑟夫环问题)
生活随笔
收集整理的這篇文章主要介紹了
ACM-ICPC 2018 沈阳赛区现场赛 K. Let the Flames Begin (约瑟夫环问题)
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
題目鏈接:
題意:有 n 個人圍成一個圈,從 1 開始報到第 k 個人出環,問第 m 個出環的人是誰,n、m、k <= 1e18 且 min(m,k)<= 2e6。
題解:容易得出O(m)的遞推公式 f[n][m] = (f[n-1][m-1] + k - 1)% n + 1,初始狀態 f[n-m+1][1]容易得出,當 m 小的時候用該公式計算。考慮 k 大 m 小的情況下,遞推式的取膜很多情況下沒有用到,可以用乘法代替加法加速遞推的過程:
當前狀態為f[a][b] = c, 經過 x 次加法后的狀態為 f[a+x][b+x] = c + k * x,假設經過 x 次加法之后需要取模,有
c + k * x > a + x? ?→? ?x > (a - c)/ (k - 1)? ?
得到該不等式后便可以計算出另一種情況了,還要注意 k = 1 需要特判。
?
1 #include <bits/stdc++.h> 2 using namespace std; 3 #define ll long long 4 #define ull unsigned long long 5 #define mst(a,b) memset((a),(b),sizeof(a)) 6 #define mp(a,b) make_pair(a,b) 7 #define pi acos(-1) 8 #define pii pair<int,int> 9 #define pb push_back 10 const int INF = 0x3f3f3f3f; 11 const double eps = 1e-6; 12 const int MAXN = 2e6 + 10; 13 const int MAXM = 1e8 + 10; 14 const ll mod = 1e9 + 7; 15 16 ll f[MAXN]; 17 18 int main() { 19 #ifdef local 20 freopen("data.txt", "r", stdin); 21 // freopen("data.txt", "w", stdout); 22 #endif 23 int cas = 1; 24 int t; 25 scanf("%d",&t); 26 while(t--) { 27 ll n,m,k; 28 scanf("%lld%lld%lld",&n,&m,&k); 29 printf("Case #%d: ",cas++); 30 if(m <= k) { 31 f[1] = k % (n - m + 1); 32 if(f[1] == 0) f[1] = n - m + 1; 33 for(ll i = 2; i <= m; i++) 34 f[i] = (f[i - 1] + k - 1) % (n - m + i) + 1; 35 printf("%lld\n",f[m]); 36 } else { 37 if(k == 1) printf("%lld\n",m); 38 else { 39 ll a = n - m + 1, b = 1; 40 ll c = k % a, x = 0; 41 if(c == 0) c = a; 42 while(b + x <= m) { 43 a += x, b += x, c += k * x; 44 c %= a; 45 if(c == 0) c = a; 46 x = (a - c) / (k - 1) + 1; 47 } 48 c += (m - b) * k; 49 c %= n; 50 if(c == 0) c = n; 51 printf("%lld\n",c); 52 } 53 } 54 } 55 return 0; 56 }?
轉載于:https://www.cnblogs.com/scaulok/p/9911819.html
總結
以上是生活随笔為你收集整理的ACM-ICPC 2018 沈阳赛区现场赛 K. Let the Flames Begin (约瑟夫环问题)的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: flume + kafka
- 下一篇: Codeforces 815C. Kar