zoukankan      html  css  js  c++  java
  • 约瑟夫环问题

    题目

    每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。HF作为牛客的资深元老,自然也准备了一些小游戏。其中,有个游戏是这样的:首先,让小朋友们围成一个大圈。然后,他随机指定一个数m,让编号为0的小朋友开始报数。每次喊到m-1的那个小朋友要出列唱首歌,然后可以在礼品箱中任意的挑选礼物,并且不再回到圈中,从他的下一个小朋友开始,继续0...m-1报数....这样下去....直到剩下最后一个小朋友,可以不用表演,并且拿到牛客名贵的“名侦探柯南”典藏版(名额有限哦!!^_^)。请你试着想下,哪个小朋友会得到这份礼品呢?(注:小朋友的编号是从0到n-1)

    可以用STL中的list解决,也可以用vector来解决

    1. list

    int LastRemaining_Solution(int n, int m)
    {
    if(n <= 0 || m <= 0)
    return -1;
    list<int> list_child;
    for(int i = 0; i < n; i++)
    {
    list_child.push_back(i);
    }
    int step = 0;
    list<int>::iterator it = list_child.begin();
    while(list_child.size() > 1)
    {
    if(it == list_child.end())
    {
    it = list_child.begin();
    }
    else if(step == m-1)
    {
    list<int>::iterator temp = ++it;
    list_child.erase(--it);
    step = 0;
    it = temp;
    }
    else
    {
    step++;
    it++;
    }

    }
    return list_child.front();
    }

    2. vector

    int LastRemaining_Solution(int n, int m)
    {
    if(n <= 0 || m <= 0)
    return -1;
    vector<int> v_child(n, 0);
    int i = 0;
    int step = 0;
    int count = n;
    while(count > 1)
    {
    i++;
    if(i == n)
    i = 0;
    if (v_child[i] == 1)
    {
    continue;
    }
    step++;
    if(step == m-1)
    {
    v_child[i] = 1;
    step = 0;
    count--;
    i++;
    if(i == n)
    i = 0;
    while (v_child[i] == 1)
    {
    i++;
    if(i == n)
    i = 0;
    }
    }
    }
    return i;
    }

  • 相关阅读:
    学习subprocess模块...
    【排列组合】
    【约瑟夫问题】
    【craps赌博游戏】
    【洗扑克牌(乱数排列)】
    【最大访客数】
    【后序式的运算】
    【中序式转后序式】
    【python基础】之元组 集合 字典
    【费式数列(Fibonacci数列)】
  • 原文地址:https://www.cnblogs.com/mengjuanjuan/p/10464937.html
Copyright © 2011-2022 走看看