C + + and Python implementations of Apple-splitting problems

Source: Internet
Author: User

A very interesting question. How could Xiaoming's apples be identical?


Obviously this is not the point. The focus is on how to abstract the problem.


If from M apples, take out n apples, ask there are several possibilities, it is obvious that this is a typical combinatorial problem;

Combination Algabra;


If you divide m apples into n parts. There are obviously only 1 possibilities.


Divide the apples into n heaps, for the possibility, I can not think of a mathematical model 1:30. Naturally, a mathematical approach was thought of: iterative approximation and recursion.


The topic additional explanation, 1,3,1 and 1,1,3 calculate same kind of division method. Its distribution may be equivalent to decreasing or incrementing apples.


So we begin to count recursively:


Recursive operation: Traversing m~0, if there is a small element before the array, indicating that this is the maximum possible in descending case, the new element is assigned a value m, and the remaining elements are recursively manipulated.

Recursive exit criteria: the last digit of the array is also assigned (the remaining element is exactly less than or equal to the previous number).

Recursive exit Operation: Counter plus one. If you prefer, you can output the array at this time.


C + + implementation algorithm (worth my own practice and fine products)

#include   "stdafx.h" #include  <iostream>int Count = 0;using namespace  Std;void printarr (Int dishnum, int* arr) {for  (int i = 0; i  < dishnum; i++) {for  (int j = 0; j < arr[i]; j++) cout  <<  "(vIv)";cout <<  "";} Cout << endl;} Void allocation (Int applenumleft, int dishnum, int idx, int* arr) {if   (idx ==  (dishnum - 1)) {if  (Arr[idx - 1] >= applenumleft) {arr[idx] = applenumleft; count++;p Rintarr (Dishnum, arr); return;} Elsereturn;} else{for  (int j = applenumleft; j >= 0; j--) {if  (idx ==  0) {arr[idx] = j;allocation (applenumleft - j, dishnum, idx + 1,  arr);} else{if  (Arr[idx - 1] >=&nbsP;J) {arr[idx] = j;allocation (applenumleft - j, dishnum, idx + 1,  arr);}}}} Int _tmain (int argc, _tchar* argv[]) {int m, n;cin >> m > > n;int *a = new int[n];allocation (M, n, 0, a);cout <<  count<<endl;delete[]a;a = null;return 0;}

Verify that the algorithm is correct.


For each recursive layer, the loop in the recursive function shortens one layer. Until you reach the last pass. If no minimum value exists, the counter is returned without accumulating.


Then a Python transcription algorithm is used. Key points in the transcription process:

    1. Python does not have a reference to the delivery, instead the global list.

    2. The For loop is an iterator.

    3. The global list needs to be initialized.

    4. Thanks to the direct print list, a print function is omitted (so no Apple t_t)

    5. It's strange to have no object-oriented. Should create an Apple dispenser class what.

#-*-coding:utf-8-*def allocate (M,N,IDX):    global a ,count     if idx==n-1:        if a[idx-1]>=m :             a[idx]=M             count+=1             print a            return         else:             return    else:        for i  in reversed (range (0,m+1)):             if idx==0:                 a[idx]=i   &nBsp;            allocate (M-i,N,idx+1)              else:                 if a[idx-1]>=i:                     a[idx]=i                      Allocate (m-i,n,idx+1) if __name__== ' __main__ ':     m,n=raw_input ("Please enter the number of apples and plates and separate them with spaces \ n") ). Strip (). Split ()     a=[]    for i in range (0,int (N)):         a.append (0)     count=0     allocate (int (M), int (N), 0)     print count

The difference between the visual simplicity of two pieces of code is obvious. Python is inherently readable and easy to write (indentation is much better than curly braces.) ), the code is nearly half short, perhaps unfriendly to ROP: P (rop=resume oriented programming)

C + + and Python implementations of Apple-splitting problems

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.