C + + Joseph ring

Source: Internet
Author: User

Joseph Ring:

Known n individuals (denoted by number 1,2,3...N) sit around a table. From the person numbered K began to count, the number to m of the person out of the man, and his next person from 1 began to count, the number to m of the person again, according to this rule repeat until the round table all the people out.

For example: n = 9, k = 1, M = 5 "solution" the order of the outgoing persons is 5, 1, 7, 4, 3, 6, 9, 2, 8.

1 intMain ()//Joseph Ring2 {3     intn=9, m=5, k=2;//N is the number of people (ref. 1,2,......,x), M is the dequeue number, K is the starting person number4     intj=0, l=0;5     inta[Ten];6      for(intI=1; i<=9; i++)7     {8a[i]=1;9     }Ten  One      while(l<N) A     { -          for(intI=1; i<=n;i++)  -         { the             if(a[i]==1)  -             { -J + +; -                 if(j==m) +{//Meet the Dequeue number -a[i]=0; +                     if(i==n&&k>1)  A                     { atcout<<1<<Endl; -                     } -                     Else -                     { -cout<<i+ (K-1) <<Endl; -                     } inj=0; -l++; to                 } +             } -         } the     } *  $}

By the way, I enclose a mathematical thought of Joseph Ring solution, which requires a little different.

is a total of n individuals, to find the man m out of the circle, the final circle of the number of people.

int fun (int n, int m)
{
int I, r = 0;
for (i = 2; I <= n; i++)
R = (r + m)% i;
return r+1;
}

C + + Joseph ring

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.