King's Game hdu5643(约瑟夫环变形)

King's Game

Time Limit: 2000/1000 MS (Java/Others)    Memory Limit: 65536/65536 K (Java/Others)
Total Submission(s): 842    Accepted Submission(s): 464


Problem Description
In order to remember history, King plans to play losephus problem in the parade gap.He calls n(1n5000) soldiers, counterclockwise in a circle, in label 1,2,3...n.

The first round, the first person with label 1 counts off, and the man who report number 1 is out.

The second round, the next person of the person who is out in the last round counts off, and the man who report number 2 is out.

The third round, the next person of the person who is out in the last round counts off, and the person who report number 3 is out.



The N - 1 round, the next person of the person who is out in the last round counts off, and the person who report number n1 is out.

And the last man is survivor. Do you know the label of the survivor?
 

Input
The first line contains a number T(0<T5000), the number of the testcases.

For each test case, there are only one line, containing one integer n, representing the number of players.
 

Output
Output exactly T lines. For each test case, print the label of the survivor.
 

Sample Input
 
 
223
 
Sample Output
 
 
22Hint:For test case #1:the man who report number $1$ is the man with label $1$, so the man with label $2$ is survivor.For test case #1:the man who report number $1$ is the man with label $1$, so the man with label 1 is out. Again the the man with label 2 counts $1$, the man with label $3$ counts $2$, so the man who report number $2$ is the man with label $3$. At last the man with label $2$ is survivor.

首先什么是你约瑟夫环?

n个人站成一圈, 编号为1-n, 开始报数, 报到q的淘汰, 求最后的赢家;

对于n, 与 q, ans=(ans+q)%i;q表示报数为q的淘汰, i表示本局有多少人(n), ans表示上局获胜的人的下标(下标由0-(n-1)编号);

而此题中q是变化的, 需要稍微变形;

#include<iostream>
using namespace std;
int main(){
	int n;
	int T;
	cin >> T;
	while(T--){
		cin >> n;
		int ans=0;
		int k=n-1;//约瑟夫环是倒着推的, 所以k由n-1开始;
		for(int i=2; i<=n; i++){
			ans=(ans+k)%i;
			k--;
		}
		cout << ans+1 << endl;
	}
	return 0;
}  








  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值