约瑟夫问题

来源:互联网 发布:淘宝刷差评平台 编辑:程序博客网 时间:2024/04/28 13:00

这是算法里很常规的一个例题。我是这样写的:

#include <iostream>

using namespace std;

typedef struct _Person{
    int id;
    int death;
    _Person *next;
} Person;

int main()
{
    int n, m, deathCount = 0;
    cin >> n >> m;
    Person *person = new Person[n];
    Person *p = person;
    for (int i = 0; i < n; i++)
    {
        person[i].id = i+1;
        person[i].death = 0;
        if (i == n-1)
        {
            person[i].next = &person[0];
        }
        else
        {
            person[i].next = &person[i + 1];
        }
    }
    while(deathCount != n)
    {
        for (int i = 0; i < m-1; i++)
        {
            if (i == m-2)
            {
                p->next->death = 1;
                cout << p->next->id << endl;
                p->next = p->next->next;
                deathCount++;
            }
            p = p->next;
        }
    }
    system("pause");
    return 0;
}

但是别人是这样写的:

#include <iostream>
#include <list>
using namespace std;

int main()
{
    int total  = 0;
    cout << "Please input total number of people : ";
    cin >> total;

    int number = 0;
    cout << "Please input selected number : ";
    cin >> number;

    int last = 0; // f(1) = 0
    for(int i = 2; i <= total; ++i)
    {
        last = (last + number) % i;
    }
    cout << "The last one is : " << last + 1 << endl;
    system("pause");
    return 0;
}

感觉自己很矬有木有?心累不想说话,明天再讲原理。

原创粉丝点击