編程演算法 - 多重部分和問題 代碼(C)

來源:互聯網
上載者:User

標籤:mystra   編程演算法   多重部分和問題   動態規劃   c   

多重部分和問題 代碼(C)


本文地址: http://blog.csdn.net/caroline_wendy


題目: 有n種不同大小的數字a, 每種各m個. 判斷是否可以從這些數字之中選出若干使它們的和恰好為K.


使用動態規劃求解(DP)

方法1: dp[i+1][j] = 用前n種數字是否能加和成j, 時間複雜度O(nKm), 不是最優.


方法2: dp[i+1][j] = 用前i種數加和得到j時, 第i種數最多能剩餘多少個. 時間複雜度O(nK).

例如: n=3, a={3,5,8}, m={3,2,2}, K=17時.

i\j 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
起始 0 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1 -1
0(3,3) 3 -1 -1 2 -1 -1 1 -1 -1 0 -1 -1 -1 -1 -1 -1 -1 -1
1(5,2) 2 -1 -1 2 -1 1 2 -1 1 2 0 -1 -1 0 1 -1 -1 -1
2(8,2) 2 -1 -1 2 -1 2 2 -1 2 2 2 1 -1 1 1 -1 1 1

代碼:

/* * main.cpp * *  Created on: 2014.7.20 *      Author: spike *//*eclipse cdt, gcc 4.8.1*/#include <stdio.h>#include <memory.h>class Program {static const int MAX_N = 100;int n = 3;int K = 17;int a[MAX_N] = {3,5,8};int m[MAX_N] = {3,2,2};bool dp[MAX_N+1][MAX_N+1];public:void solve() {dp[0][0] = true;for (int i=0; i<n; ++i) {for (int j=0; j<=K; ++j) {for (int k=0; k<=m[i]&&k*a[i]<=j; ++k) {dp [i+1][j] |= dp[i][j-k*a[i]]; //或運算}}}if (dp[n][K]) printf("result = Yes\n");else printf("result = No\n");}};class Program2 {static const int MAX_N = 100;static const int MAX_K = 20;int n = 3;int K = 17;int a[MAX_N] = {3,5,8};int m[MAX_N] = {3,2,2};int dp[MAX_K+1];public:void solve() {memset(dp, -1, sizeof(dp));dp[0] = 0;for (int i=0; i<n; ++i) {for (int j=0; j<=K; ++j) {if (dp[j] >= 0) {dp[j] = m[i];} else if (j < a[i] || dp[j-a[i]]<=0){dp[j] = -1;} else {dp[j] = dp[j-a[i]]-1;}}}if (dp[K]>=0) printf("result = Yes\n");else printf("result = No\n");}};int main(void){Program2 iP;iP.solve();return 0;}

輸出:

result = Yes










編程演算法 - 多重部分和問題 代碼(C)

相關文章

聯繫我們

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