1. 程式人生 > >[動態規劃]Tak and Cards

[動態規劃]Tak and Cards

das 三次 span pan num nts com for integer

題目描述

Tak has N cards. On the i-th (1≤i≤N) card is written an integer xi. He is selecting one or more cards from these N cards, so that the average of the integers written on the selected cards is exactly A. In how many ways can he make his selection?

Constraints
1≤N≤50
1≤A≤50
1≤xi≤50
N,A,xi are integers.
Partial Score
200 points will be awarded for passing the test set satisfying 1≤N≤16.

輸入

The input is given from Standard Input in the following format:
N A
x1 x2 … xN

輸出

Print the number of ways to select cards such that the average of the written integers is exactly A.

樣例輸入

4 8
7 9 8 9

樣例輸出

5

提示

The following are the 5 ways to select cards such that the average is 8:
Select the 3-rd card.
Select the 1-st and 2-nd cards.
Select the 1-st and 4-th cards.
Select the 1-st, 2-nd and 3-rd cards.
Select the 1-st, 3-rd and 4-th cards.

思路:很顯然,是要求算技術分享圖片,這裏dp[i][j]表示取i個值和為j的取法數。C(n,1)+C(n,2)+...+C(n,n)=2^n-1,暴力枚舉顯然超時;考慮找到dp[i][j]的遞推式; 容易想到dp[i][j]+=dp[i-1][j-a[k]](k=1~n),也就是說取i個值和為j的方法數等於取i-1個值和為j-a[k](k=1~n)的方法數之和?顯然是不對的,拿樣例舉例,計算dp[3][24](初值為0)時,在k=1時,dp[3][24]+=dp[2][17],k=2時,dp[3][24]+=dp[2][15],k=3時,dp[3][24]+=dp[2][16]...暫且先看k=1~3這一部分,並暫且認為已計算出dp[2][j]的所有結果都是正確的,那dp[3][24]在被k=1~3更新時,很顯然能看見取前三個數這種取法被重復計算了三次(也就是這一種取法被視為了三種取法),那如何避免這樣的重復計算呢——在計算dp[i][j]考慮取a[k]時,取滿j-a[k]的另外i-1個值只能從a[1~k]之中取。這樣的話,就變成了考慮用a[k]更新所有的dp[i][j](i=k~1,j=sum[k]~a[k])(註意用a[k]更新dp[i][j]的順序——更新dp[i][j]要用到dp[i-1][j-a[k]],不能用a[k]先把dp[i-1][j-a[k]]給更新了),而不是考慮將dp[i][j]用所有的a[k](k=1~n)去更新; AC代碼:
#include <iostream>
#include
<cstdio> typedef long long ll; using namespace std; int a[55]; int sum[55]; ll dp[55][2505]; int main() { int n,A; scanf("%d%d",&n,&A); for(int i=1;i<=n;i++) {scanf("%d",&a[i]); sum[i]=sum[i-1]+a[i];} dp[0][0]=1; for(int k=1;k<=n;k++){ for(int i=k;i>=1;i--){ for(int j=sum[k];j>=a[k];j--){ dp[i][j]+=dp[i-1][j-a[k]]; } } } ll ans=0; for(int i=1;i<=n;i++) ans+=dp[i][i*A]; printf("%lld\n",ans); return 0; }

另外,關於動態規劃和遞推,我已經分不清了(#°Д°)

[動態規劃]Tak and Cards