• 约瑟夫环问题


    题目

    每年六一儿童节,牛客都会准备一些小礼物去看望孤儿院的小朋友,今年亦是如此。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;
    }

  • 相关阅读:
    hdu1430 魔板(康拓展开 bfs预处理)
    网络流EdmondsKarp算法模板理解
    poj3020 建信号塔(匈牙利算法 最小覆盖边集)
    bzoj 2465 小球
    bzoj 1822 冷冻波
    bzoj 1040 骑士
    Codeforces Round #460 (Div. 2)
    bzoj 1072 排列perm
    Codeforces Round #459 (Div. 2)
    bzoj 1087 互不侵犯King
  • 原文地址:https://www.cnblogs.com/mengjuanjuan/p/10464937.html
Copyright © 2020-2023  润新知