题目
题目链接:http://acm.hdu.edu.cn/showproblem.php?pid=5643
题目来源:BestCoder#75
简要题意:约瑟夫问题,每次报的次数是从 1到n−1 。
题解
经典的约瑟夫问题,可以进行递推的求解。
每次求解从 0 开始的约瑟夫,然后通过
n−1 规模的解可以推出当前的解。由于解的大小必然小于 n−1 所以直接加就行了,为了方便可以从 1 开始计数
k 。
代码
#include <iostream>
#include <cstdio>
#include <cmath>
#include <algorithm>
#include <cstring>
#include <stack>
#include <queue>
#include <string>
#include <vector>
#include <set>
#include <map>
#define fi first
#define se second
using namespace std;
typedef long long LL;
typedef pair<int,int> PII;
// head
int solve(int n, int k) {
if (n == 1) return (n + k - 1) % n;
return (k + solve(n-1, k+1)) % n;
}
int main() {
int t, n;
scanf("%d", &t);
while (t--) {
scanf("%d", &n);
printf("%d\n", solve(n, 1) + 1);
}
return 0;
}