演算法實驗之動態規劃

來源:互聯網
上載者:User

設有n種不同面值的硬幣,各硬幣的面值存於數組T[1:n]中。現要用這些面值的硬幣來找錢,可以實用的各種面值的硬幣個數不限。當只用硬幣面值T[1],T[2],…,T[i]時,可找出錢數j的最少硬幣個數記為C(i,j)。若只用這些硬幣面值,找不出錢數j時,記C(i,j)=∞。 

輸入結果儲存在1.txt中,輸出結果儲存在2.txt中。

#include<iostream>#include <fstream>using namespace std;int change_coin(int a[],int k,int ch){int **c=new int*[k];for(int i=0;i<k;i++)c[i]=new int[ch+1];for(i=0;i<=ch;i++){if(ch%a[0]==0)c[0][i]=i/a[0];elsec[0][i]=INT_MAX;}for(int j=1;j<k;j++){for(i=0;i<=ch;i++)if(i<a[j])c[j][i]=c[j-1][i];elsec[j][i]=c[j-1][i]<c[j][i-a[j]]+1?c[j-1][i]:c[j][i-a[j]]+1;}return c[k-1][ch];}int main(){int k;int a[3];int ch;ifstream in("1.txt");ofstream out("2.txt");in>>k;for(int i=0;i<k;i++)in>>a[i];cout<<"請輸入待找錢數"<<endl;cin>>ch;int res=change_coin(a,k,ch);cout<<"找錢個數為:"<<res<<endl;out<<res;in.close();out.close();return 1;}

聯繫我們

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