poj 1664 放蘋果(dfs)

來源:互聯網
上載者:User

標籤:

放蘋果
Time Limit: 1000MS   Memory Limit: 10000K
Total Submissions: 30284   Accepted: 19098

Description

把M個同樣的蘋果放在N個同樣的盤子裡,允許有的盤子空著不放,問共有多少種不同的分法?(用K表示)5,1,1和1,5,1 是同一種分法。

Input

第一行是測試資料的數目t(0 <= t <= 20)。以下每行均包含二個整數M和N,以空格分開。1<=M,N<=10。

Output

對輸入的每組資料M和N,用一行輸出相應的K。

Sample Input

17 3

Sample Output

8

分析:簡單的DFS,可以把問題想象成把一個整數M分解成N個數相加,其中符合加法交換律的是一種情況。為保證不重複(即不會出現加法交換律的情況出現),可以令分解的N個數呈非遞增(或非遞減)順序排列,所以下面的遞迴函式裡,有一個參數是前一個數的大小,在本次遞迴裡分配的數要不大於前一個數的大小。

Java AC 代碼

import java.util.Scanner;public class Main {        static int apples;    static int plates;        static int plans;        public static void main(String[] args) {        Scanner sc = new Scanner(System.in);        int testNumber = sc.nextInt();        for(int i = 1; i <= testNumber; i++) {            apples = sc.nextInt();            plates = sc.nextInt();            plans = 0;            dfs(apples, plates, apples + 1);            System.out.println(plans);        }    }        /**     *      * @param leftApples 剩餘的蘋果數     * @param leftPlates 剩餘的盤子數     * @param pre 前一個盤子放的蘋果數。要保證當前盤子放的蘋果數小於前一個盤子放的蘋果數,這樣可以避免重複(當然也可以把順序反過來放)     */    public static void dfs(int leftApples, int leftPlates, int pre) {                if(leftApples == 0 && leftPlates >=0) { //蘋果沒了,但盤子還有或恰好沒有,則方案數加1            plans ++;            return;        }                if(leftPlates <= 0)            return;        for(int i = leftApples; i > 0; i--) {              if(i > pre)     //如果當前盤子要放的蘋果數大於前一個盤子的蘋果數,則跳過                continue;            findPlans(leftApples - i, leftPlates - 1, i);        }            }}

 

poj 1664 放蘋果(dfs)

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.