UVA 1394 And Then There Was One(约瑟夫环变形)
2016-10-02 23:02
411 查看
一共有n个数,那么设0~n-1代表这些数的位置,从0开始是为了取模方便,每隔k删掉一个数,那么第一次删掉的是k-1,然后重新排列
k -> 0
k+1 -> 1
k+2 ->2
.....
k-2 -> n-2
把右边的位置设为重新编号后的x
从上面的规律中可以看出,目前n-1个人的位置映射到n个人的位置就是(x+k)%n,所以根据这个规律,可以用n-1推出n,用n-2推出n-1,这样就可以建立递推了。
设f[i]为共i个人最后留下来的胜利者,那么根据上面的描述可以定义f[i]=(f[i-1]+k)%i。
但是这里是从m开始的,所以需要变形。
现在是第m个人先失败,所以m-1个人先出去就可以了。//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/10/2.
// Mail:1016427040@qq.com or jasonshaosjj@gmail.com
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n,k,m;
while(scanf("%d%d%d",&n,&k,&m)&&(n+k+m))
{
int ans=0;
for(int i=2;i<n;i++)
ans=(ans+k)%i;
ans=(ans+m)%n;
cout<<ans+1<<endl;
}
return 0;
}
k -> 0
k+1 -> 1
k+2 ->2
.....
k-2 -> n-2
把右边的位置设为重新编号后的x
从上面的规律中可以看出,目前n-1个人的位置映射到n个人的位置就是(x+k)%n,所以根据这个规律,可以用n-1推出n,用n-2推出n-1,这样就可以建立递推了。
设f[i]为共i个人最后留下来的胜利者,那么根据上面的描述可以定义f[i]=(f[i-1]+k)%i。
但是这里是从m开始的,所以需要变形。
现在是第m个人先失败,所以m-1个人先出去就可以了。//
// main.cpp
// Richard
//
// Created by 邵金杰 on 16/10/2.
// Mail:1016427040@qq.com or jasonshaosjj@gmail.com
// Copyright © 2016年 邵金杰. All rights reserved.
//
#include<iostream>
#include<cstdio>
#include<cstring>
#include<algorithm>
using namespace std;
int main()
{
int n,k,m;
while(scanf("%d%d%d",&n,&k,&m)&&(n+k+m))
{
int ans=0;
for(int i=2;i<n;i++)
ans=(ans+k)%i;
ans=(ans+m)%n;
cout<<ans+1<<endl;
}
return 0;
}
相关文章推荐
- 【约瑟夫环变形】UVa 1394 - And Then There Was One
- uva 1394 - And Then There Was One(约瑟夫环)
- UVALive - 3882 And Then There Was One (约瑟夫环变形)@
- LA 3882 - And Then There Was One 【约瑟夫环变形】
- UVa 1394: And Then There Was One
- Poj 3517 And Then There Was One(约瑟夫环变形)
- UVa:1394 And Then There Was One
- UVA 1394/POJ 3517 And Then There Was One
- UVa1394 - And Then There Was One
- uva live 3882 And Then There Was One 约瑟夫环
- UVa 1394: And Then There Was One
- UVALive 3882 And Then There Was One 约瑟夫环问题
- UVA 1394 POJ 3517 And Then There Was One (双向循环链表和递推)
- 1394 - And Then There Was One(约瑟夫问题变形)DP
- UVALive 3882 And Then There Was One 约瑟夫环问题
- UVA - 1394 And Then There Was One
- UVA1394 And Then There Was One
- UVA 1394 And Then There Was One / Gym 101415A And Then There Was One / UVAlive 3882 And Then There Was One / POJ 3517 And Then There Was One / Aizu 1275 And Then There Was One (动态规划,思维题)
- UVA 1394 And Then There Was One
- uva 1394 - And Then There Was One