Poj1012_Joseph
一、Description
remaining person will be saved. Joseph was smart enough to choose the position of the last remaining person, thus saving his life to give us the message about the incident. For example when n = 6 and m = 5 then the people will be executed in the order 5, 4,
6, 2, 3 and 1 will be saved.
Suppose that there are k good guys and k bad guys. In the circle the first k are good guys and the last k bad guys. You have to determine such minimal m that all the bad guys will be executed before the first good guy.
二、问题分析
刚开始的时候没看懂英文,找了个翻译:约瑟夫问题是个有名的问题:N个人围成一圈,从第一个开始报数,第M个将被杀掉,最后剩下一个,其余人都将被杀掉。例如N=6,M=5,被杀掉的人的序号为5,4,6,2,3。最后剩下1号。假定在圈子里前K个为好人,后K个为坏人,你的任务是确定这样的最少M,使得所有的坏人在第一个好人之前被杀掉。这道题感觉不容易,看了很多提示才有点感觉。
开始的时候总想着用什么数据结构实现这个环,什么链表,栈之类的。又总是琢磨从0开始还是从1开始,傻逼逼地在那比对公式的输出结果数字。后来发现完全没有必要,因为好人与坏人总是分在两个K内的。好人在小的那一部分,坏人在较大的那部分。所以只要下个要杀的人>k就可以继续循环。这里比较坑爹的是,测试数据里面有相同的K,如果不用记忆化存储的话,可能会超时。所以,这里好多人就干脆打表了。
什么是打表呢?如果第一个测试用例让你求第100个,那么你可以将前100个数据在自己电脑里算好再存起来,这样如果题目再问到小于100的情况,就我们就可以直接输出了,相当于查表输出,时间耗时就自然少的多了。如果第二个测试用例让我们求第200个,那么我们就从第101个算起,算出的结果继续存起来,以备下一次的实用,如此类推,这个存起来的过程就叫做打表。(打表法貌似被不少人鄙视)
不用打表其实也是可以过的,前辈们总结了三点,再次小弟引用一下:
1.要kill的人的位置公式p=(p+m-1)%rest+1
2.kill的位置<k就break,此时剩下的人rest等于k就成功
3.m不要递增,如6个人,m取1,2,3第一次就杀了好人了,没意义。m是k+1的整数倍或者k+1的整数倍加1,这样会提高不少。
import java.util.Scanner; public class Poj1012_Joseph { public static void main(String[] args) {
Scanner cin=new Scanner(System.in);
int res[]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};//1~14,0位置不存放
int k=0;
while((k = cin.nextInt()) != 0){
int m=0;
if(res[k]==0){
while(true){
if(m/k==0)
m += k+1;
else
m ++;
int rest=2 * k;
int pos=0;
while(true){
pos=(pos+m-1)%rest+1; //位置公式
if(pos>k){
pos--;
rest--;
}else{
break;
}
}
if(rest==k){
res[k]=m;
break;
}
}
}
System.out.println(res[k]);
}
}
}
版权声明:本文为博主原创文章,未经博主允许不得转载。
Poj1012_Joseph的更多相关文章
随机推荐
- intellij idea 自动生成setter getter
windows下: alt + insert,然后选择要生成的成员. mac下: command + N
- GCD多线程在swift中的变化
1.异步线程加载主线程刷新 DispatchQueue.global().async { // TODO:执行异步线程网络请求 DispatchQueue.main.async(execute: { ...
- java中枚举类型的使用
Java 枚举(enum) 详解7种常见的用法 JDK1.5引入了新的类型——枚举.在 Java 中它虽然算个“小”功能,却给我的开发带来了“大”方便. web项目里实体类使用枚举类型: 一般在该实体 ...
- JSP 分页代码
jsp 分页模板 后台分页代码: 说明: 在 com.zc.domain 包下: PageBean.java 文件 package cn.itcast.customer.domain; impor ...
- 数组中去除重复的对象的简单方法and&&的使用
const arr = [ { name:'tom', age:15 }, { name:'rose', age:17 }, { name:'tom', age:11 }, { name:'rose' ...
- linux 中sort命令 按照指定列排序
sort怎样按指定的列排序0000 27189 41925425065f 15 419254250663 7 419254250675 5 419254250691 76 419254250693 2 ...
- 通过systemd配置Docker
1. systemd Service相关目录 通常情况下,我们有3种方式可以配置etcd中的service.以docker为例,1)在目录/etc/systemd/system/docker.serv ...
- (转载)DataTable与List<T>相互转换
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...
- 有关java之反射的使用
1 public class Demo02 { 2 @SuppressWarnings("all") 3 public static void main(String[] args ...
- session不能使用 ASP.NET MVC
在web.coonfig中添加 <sessionState mode=" /> 如: <system.web> //... <sessionState mode ...