2019上海網絡賽(J)Stone gameDP揹包

CSL loves stone games. He has n stones; each has a weight ai. 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 10^9 + 7.

Formerly, you are given a labelled multisetS=a1,a2,,anS={a1,a2,…,an}, 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))\left(Sum(S') \ge Sum(S-S') \right) \land \left(\forall t \in S', Sum(S') - t \le Sum(S-S') \right) .

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 n(1≤n≤300), which means the number of stones. The second line are n space-separated integers a1,a2,,ana_1,a_2,…,a_n (1≤ai≤500).

OutputFile

For each case, a line of only one integer t — the number of possible plans. If the answer is too large, please output the answer modulo 10^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.

鏈接:

https://nanti.jisuanke.com/t/41420

題意:

有一堆石頭,現在讓你選從中選出幾個石頭,使得選出石頭的總和大於等於剩餘石頭的總和並且從選出的石頭中拿出任何一塊石頭小於等於剩餘石頭的總和。

思路:

因爲從選出的石頭中選出如何一塊石頭,那麼我們要拿出最小的一塊石頭。所以我們可以從大到小排序一下。dp[k]表示選出石頭重量爲k的方案數,然後就01揹包。因爲我們的石頭是從大到小排的,那麼選第i塊石頭爲最小石頭並且總重量爲k的方案數就是dp[k-a[i]]。

代碼:

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