2019上海網絡賽(J) 計蒜客 - 41420 Stone game(DP)

題幹:

CSL loves stone games. He has n stones; each has a weight aia_i . CSL wants to get some stones. The rule is that the pile he gets should have a higher or equal total weight than the rest; however if he removes any stone in the pile he gets, the total weight of the pile he gets will be no higher than the rest. It’s so easy for CSL, because CSL is a talented stone-gamer, who can win almost every stone game! So he wants to know the number of possible plans. The answer may be large, so you should tell CSL the answer modulo 10910^9+ 7.Formerly, you are given a labelled multiset
S={a1,a2,,an}S=\{a_1,a_2,\ldots,a_n\}, find the number of subsets of S: S={ai1,ai2,,aik}S'=\{a_{i_1}, a_{i_2}, \ldots, a_{i_k} \} such that
Sum(S)Sum(SS))(tS,Sum(S)tSum(SS)).Sum(S ′ )≥Sum(S−S ′ ))∧(∀t∈S ′ ,Sum(S ′ )−t≤Sum(S−S ′ )).

InputFile
The first line an integer T (1≤T≤10), which is the number of cases.
For each test case, the first line is an integer nn (1≤n≤300), which means the number of stones. The second line are nn space-separated integers a 1 ,a 2 ,…,an (1≤ai​ ≤500).
OutputFile
For each case, a line of only one integer tt — the number of possible plans. If the answer is too large, please output the answer modulo109+710^9+7

樣例輸入
2
3
1 2 2
3
1 2 4
樣例輸出
2
1
樣例解釋
In example 1, CSL can choose the stone 1 and 2 or stone 1 and 3.
In example 2, CSL can choose the stone 3.

思路:

總結下題意,你有一堆石頭,你需要選出其中的若干個石頭,使得選出石頭的重量大於未選出的石頭的重量①,並且去掉選出石頭中的任意的一個,新的石頭堆重量小於未選出的石頭的重量②。求有多少種方案滿足題意。

因爲是求總方案數,所以考慮需要使用DP來做。考慮條件①,它將總重量分成兩部分,總重量sum,選中的重量sum1,餘下的重量sum-sum1,條件① => sum1>=sum-sum1。
dp[i]表示重量爲i的石頭堆的方案數。

考慮條件②,因爲是任選,所以我們考慮影響重量最小的變量(因爲去掉最小的滿足,去掉大的一定滿足),所以可以先將石頭從大到小排序,以當前重量x[i]爲最小值的石頭堆即x[1]+x[2]…+x[i]。這樣通過確定一個石頭堆中的最小值,枚舉石頭堆總質量,就可以獲得答案。

dp[j]=dp[j]+dp[j-x[i]](常規dp獲得不考慮條件②的所有方案數)
if(j>=sum-sum1&&j-x[i]<=sum-sum1)
ans=(ans+dp[j-x[i]]) (加入判斷獲得答案)

#include <cstdio>
#include <cstring>
#include <iostream>
#include <algorithm>
using namespace std;
typedef  long long ll;
const int mod=1e9+7;
int dp[160000],x[4000];
bool cmp(int a,int b){
	return a>b;
}
int main() 
{
	int t,n;
	scanf("%d",&t);
	while(t--){
		scanf("%d",&n);
		int sum=0,ans=0;
		memset(dp,0,sizeof(dp));
		for(int i=1;i<=n;i++){
			scanf("%d",&x[i]);
			sum+=x[i];
		}
		dp[0]=1;
		sort(x+1,x+1+n,cmp);
		for(int i=1;i<=n;i++){
			for(int j=sum;j>=x[i];j--){
				int yu=sum-j;
				dp[j]=(dp[j]+dp[j-x[i]])%mod;
				if(j>=yu&&j-x[i]<=yu){
					ans=(ans+dp[j-x[i]])%mod;
				}
			}
		}
		printf("%d\n",ans%mod);
	}
	return 0;
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章