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;
    }

  • 相关阅读:
    看起来像一个输入框的input,实际上是有两个input
    Actions类的一些主要方法
    selenium通过WebDriverWait实现ajax测试,实现等页面元素加载完成
    如何判断新打开窗口是否需要切换
    鼠标悬停
    Selenium WebDriver使用IE浏览器
    Element should have been select but was input
    58同城Java面试
    2个线程ABAB或者BABA循环输出
    使多个线程循环输出099099
  • 原文地址:https://www.cnblogs.com/mengjuanjuan/p/10464937.html
Copyright © 2011-2022 走看看