“常用公式”在线计算,“设计手册”在线查询
分享到:  QQ好友和群QQ好友和群 QQ空间QQ空间 腾讯微博腾讯微博 腾讯朋友腾讯朋友
收藏收藏 分享分享 分享淘帖 支持支持 反对反对

共 1 个关于本帖的回复 最后回复于 2013-8-16 13:02

沙发
王萍 新来的 发表于 2013-8-16 13:02:04 | 只看该作者
研发埠培训中心
Actually,although this is a so traditional problem, I was always to lazy to think aboutthis or even to search for the answer.(What a shame...). Finally, by google Ifound the elegant solution for it.The keys are:1) if we shift the ids by k, namely, start fromk instead of 0, we should add the result by k%n2) after the first round, we start from k+1 (possibly % n) with n-1 elements, that is equal to an (n-1) problem while startfrom (k+1)th element instead of 0, so the answer is (f(n-1, m)+k+1)%n3) k = m-1, so f(n,m)=(f(n-1,m)+m)%n.finally, f(1, m) = 0;Now this is a O(n) solution.int joseph(int n, int m) {  int fn=0;  for (int i=2; i<=n; i++) {    fn = (fn+m)%i;  }  return fn;}hu...长出一口气。。。
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

关注我们

360网站安全检测平台