首页 > 试题广场 >

约瑟夫环

[编程题]约瑟夫环
  • 热度指数:1415 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 128M,其他语言256M
  • 算法知识视频讲解

编号为0到n-1的n个人围成一圈。从编号为0的人开始报数1,依次下去,报到m的人离开,问最后留下的一个人,编号是多少?


输入描述:
输入一行两个整数n和m。


输出描述:
输出最后一个留下来的人的编号。
示例1

输入

8 3

输出

6
n,m=list(map(int,input().split()))
r = 0
for i in range(2, n+1):
    r = (r + m) % i
print(r)
发表于 2019-09-22 19:29:28 回复(0)
import java.util.*;
public class Main{
  public static Node head;
    static class Node{
        int val;
        Node next;
        public Node(int val){
            this.val = val;
        }
    }
    public static  void   create(int count){
        int i = 0;
        Node cur = null;
        while(i <= count-1){
            Node node =  new Node(i);
            if(head == null){
                head = node;
                cur = head;
            }else{
                cur.next =node;
                cur = cur.next;
            }
            i++;
        }
        cur.next = head;
    }
  
    public static  void  solve(int n ){
         int flg = 1;
         Node pre = null;
         Node cur = head;
         while(cur != cur.next){
              if(flg != n){
                      pre = cur;
                      cur = cur.next;
                        flg++;
              }else{
                 
                      pre.next = cur.next;
                     cur = cur.next;
                     flg = 1;
              }

         }
     
        System.out.println(cur.val);

    }
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        while(sc.hasNext()){
            int m = sc.nextInt();
            int n = sc.nextInt();
            create(m);
            solve(n);
        }
      
    }
}

发表于 2021-06-17 19:34:38 回复(0)
看这个输出结果,是不是应该报到m-1的人出列...
发表于 2021-03-16 07:01:37 回复(0)
import java.util.Scanner;
public class Main{
	public static void main(String[] args)
	{
		Scanner cin = new Scanner(System.in);
		int n = cin.nextInt();
		int k = cin.nextInt();
		ListNode head = null;
		ListNode curr = null;
		ListNode help = null; //
		for (int i = 0; i < n; i++) {
			ListNode listNode = new ListNode(i);
			if (i == 0) {
				head = listNode;
				head.next = head;
				curr = head;
			} else {
				curr.next = listNode;
				listNode.next = head;
				curr = listNode;
			}
			if (i == n - 1) {
				help = curr;
			}
		}
		while (head != help) {
			for (int i = 0; i < k - 1; i++) {
				head = head.next;
				help = help.next;
			}
			head = head.next;
			help.next = head;
		}
		System.out.println(head.n);
	}

}

class ListNode
{
	int n;
	ListNode next;

	public ListNode(int i)
	{
		this.n = i;
	}
}

发表于 2020-07-24 21:08:04 回复(0)
n,m=list(map(int,input().split()))
f=[0]*(n+1)
for i in range(1,n+1):
    f[i]=(f[i-1]+m)%i# 公式法 f[n]=(f[n-1]+m)%n
print(f[n])

发表于 2019-09-09 16:49:06 回复(0)

问题信息

上传者:小小
难度:
5条回答 4117浏览

热门推荐

通过挑战的用户