编号为0到n-1的n个人围成一圈。从编号为0的人开始报数1,依次下去,报到m的人离开,问最后留下的一个人,编号是多少?
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); } } }
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; } }
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])