九度 稱號1045:百雞問題

來源:互聯網
上載者:User

標籤:

題目描寫敘述:

    用小於等於n元去買100僅僅雞。大雞5元/僅僅。小雞3元/僅僅,還有1/3元每僅僅的一種小雞,分別記為x僅僅,y僅僅,z僅僅。編程求解x,y,z全部可能解。

輸入:

    測試資料有多組,輸入n。

輸出:

    對於每組輸入,請輸出x,y,z全部可行解,依照x,y,z依次增大的順序輸出。

例子輸入:
40
例子輸出:
x=0,y=0,z=100x=0,y=1,z=99x=0,y=2,z=98x=1,y=0,z=99

  
代碼例如以下。一開始用了三重迴圈。後來略微最佳化了一下,改成了兩重迴圈:
三重迴圈的代碼:
#include <stdio.h>int main(){    int n;    int x,y,z;    while(scanf("%d",&n) != EOF){        x = 0;        y = 0;        z = 0;        int money1 = n;        for(int i = 0; i <= money1/5; i++){            x = i;            int money2 = money1 - 5 * i;            for(int j = 0; j <= money2/3; j++){                y = j;                int money3 = money2 - 3 * j;                z = 100 - x - y;                if(z >= 0 && z <= 3 * money3){                    printf("x=%d,y=%d,z=%d\n");                }            }        }    }    return 0;}
兩重迴圈代碼:
#include <stdio.h>int main(){     int n;    int x,y,z;    while(scanf("%d",&n) != EOF){        x = 0;        y = 0;        z = 0;        int money1 = n;        for(int i = 0; i <= money1/5; i++){            x = i;            int money2 = money1 - 5 * i;            for(int j = 0; j <= money2/3; j++){                y = j;                int money3 = money2 - 3 * j;                for(int k = 0; k <= money3 * 3; k++){                    z = k;                    if(x+y+z == 100){                        printf("x=%d,y=%d,z=%d\n",x,y,z);                    }                }            }        }    }    return 0;}

著作權聲明:本文博主原創文章。部落格,未經同意不得轉載。

九度 稱號1045:百雞問題

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.