• 【递归】苹果分配震荡问题


        有N个人,M个苹果,M,N>0。且每个人都用标识I(I=0, 1, 2……N-1)区分,现在要将苹果分配给人。具体做法是:每次将苹果分配给第R个人,R是随机数。如果第R个人未分配到苹果,则将苹果分给他;如果将要给第R个人分配苹果时,发现他手里已有一个苹果,则把他的苹果和将要分配的苹果分给与之相邻的人,即第R-1(R>0时)和第R+1(R+1<N)个人。只要R为边界(R=0或R=N-1)且第R个人已拥有一个苹果,则抛弃其中一个苹果,另一个苹果以相同的规则,分配给与R相邻的人。

    以下是递归算法:(writen by C plusplus on GCC or CodeBlocks)

        We have N persons and M apples.M>0 and N<0 if course. And people are distinguished by ids range from 0 to N-1.Now apples are assigned to the N persons. Specifically, every time one apple will be assigned to the No. R person and R is a random number. If No.R donot have an apple then he gets this apple. If No.R has alreay got an apple then his apple and the next one that is going to be given will be assigned to his neighbor, No.R-1(R-1>=0) and No.R+1(R+1<=N-1).For No.0 and No.N-1 person, one of these two apples will be rejected and the other will be given by the same way.

    The following is my recursive algorithm( writen by c plus plus on GCC or CodeBlocks):

     1 #include <iostream>
    2 #include <cmath>
    3 #include <ctime>
    4 using namespace std;
    5 #define SIZE 50
    6 #define APP_NUM 100
    7
    8 char array[SIZE]={0};
    9 void b(unsigned t)
    10 {
    11 if( array[t]==0 ) array[t]=1;
    12 else
    13 {
    14 array[t]=0;
    15 if(t!=0) b(t-1);
    16 if(t!=SIZE-1) b(t+1);
    17 }
    18 }
    19 void a()
    20 {
    21 srand(time(0));
    22 for(int i=0; i<APP_NUM; i++)
    23 {
    24 unsigned t = rand()%SIZE;
    25 if( array[t]==0 ) array[t]=1;
    26 else b(t);
    27 }
    28 }
    29 int main()
    30 {
    31 memset(array, 0, SIZE);
    32 a();
    33 for(size_t i=0; i<SIZE; cout <<array[i++]<<ends);
    34 return 0;
    35 }
  • 相关阅读:
    专注技术热爱生活
    js效果我的蒙板效果实现
    KMP算法
    九月份发现的好东东记录
    ATL SERVER
    不要把项目开发当做自己个人的展示舞台
    看ProMesh.NET项目领悟到的
    谈谈编译原理和其在WEB开发中的应用3
    开发更深层次的交流产品
    Hibernate3.3.2 手动配置annotation环境
  • 原文地址:https://www.cnblogs.com/zhchngzng/p/2259318.html
Copyright © 2020-2023  润新知