Let’s play a stone removing game. Initially, n stones are arranged on a circle and numbered 1, . . . , n clockwise You are also given two numbers k and m. From this state, remove stones one by one following the rules explained below, until only one remains. In step 1, remove stone m. In step 2, locate the k-th next stone clockwise from m and remove it. In subsequent steps, start from the slot of the stone removed in the last step, make k hops clockwise on the remaining stones and remove the one you reach. In other words, skip (k − 1) remaining stones clockwise and remove the next one. Repeat this until only one stone is left and answer its number.
分析:本題只關心最後一個被刪除的編號,不需要完整的刪除過程,可以用遞推法求解。假設編號爲0~n-1的n
個數排成一圈,從0開始每k個數刪除一個,最後留下數字編號記爲f(n),則f(1)= 0,f(n)=(f(n-1)+k)%n(因爲刪除一個元素之後可以把所有元素重新編號)
本題第一個刪除爲m,則ans = (m - k + 1 + f[n] + n)%n.(把這個數改成1~n之間)。
#include <cstdio>
const int N = 10000 + 5;
int f[N];
int main(int argc, char** argv) {
int n, k, m;
while(~scanf("%d%d%d",&n,&k,&m) && n){
f[1] = 0;
for(int i = 2; i <= n; i++) f[i] = (f[i-1]+ k) % i;
int ans = (m - k + 1 + f[n])%n;
if(ans <= 0) ans += n; //減法模運算,有可能爲負和零
printf("%d\n",ans);
}
return 0;
}