zoukankan      html  css  js  c++  java
  • P1077 摆花 背包DP

    题目描述

    小明的花店新开张,为了吸引顾客,他想在花店的门口摆上一排花,共m盆。通过调查顾客的喜好,小明列出了顾客最喜欢的n种花,从1到n标号。为了在门口展出更多种花,规定第iii种花不能超过(a[i])盆,摆花时同一种花放在一起,且不同种类的花需按标号的从小到大的顺序依次摆列。

    试编程计算,一共有多少种不同的摆花方案。

    输入格式

    第一行包含两个正整数n和m,中间用一个空格隔开。

    第二行有n个整数,每两个整数之间用一个空格隔开,依次表示(a1,a2,…,an)

    输出格式

    一个整数,表示有多少种方案。注意:因为方案数可能很多,请输出方案数对(1000007)取模的结果。

    输入输出样例

    输入 #1

    2 4
    3 2

    输出 #1

    2

    说明/提示

    【数据范围】

    对于(20)%数据,有(0<n≤8,0<m≤8,0≤ai≤8)

    对于(50)%数据,有(0<n≤20,0<m≤20,0≤ai≤20)

    对于(100)%数据,有(0<n≤100,0<m≤100,0≤ai≤100)

    NOIP 2012 普及组 第三题

    题解

    定义状态:(f[i][j])为前 i 种花共摆放了 j 盆的总方案数。

    易得(f[i][j] = sum_{k=0}^{a[i]}f[i-1][j-k])(第i 种花摆放了 k 盆)

    时间复杂度:(O(nm*a[i]))

    空间复杂度:(O(nm))

    此题根据状态转移方程可以将数组改为滚动数组或一维数组(同背包DP)。

    我是来水题解的,此处不贴优化代码。

    code:

    #include <iostream>
    #include <cstdio>
    using namespace std;
    const int N = 1e2 + 5, mod = 1e6 + 7;
    int read() {
        int x = 0, f = 1; char ch = getchar();
        while(! isdigit(ch)) f = (ch=='-')?-1:1, ch = getchar();
        while(isdigit(ch)) x = (x<<3)+(x<<1)+(ch^48), ch = getchar();
        return x * f;
    }
    int n, m, a[N], f[N][N];
    int main() {
        n = read(); m = read();
        for(int i = 1;i <= n;i ++) a[i] = read();
        f[0][0] = 1;
    	for(int i = 1;i <= n;i ++) {
        	for(int j = 0;j <= m;j ++) {
    	    	for(int k = 0;k <= min(j, a[i]);k ++) {
        			(f[i][j] += f[i-1][j-k]) %= mod;
    			}
    		}
    	}
    	printf("%d
    ", f[n][m]);
        return 0;
    }
    
  • 相关阅读:
    Leetcode 538. Convert BST to Greater Tree
    Leetcode 530. Minimum Absolute Difference in BST
    Leetcode 501. Find Mode in Binary Search Tree
    Leetcode 437. Path Sum III
    Leetcode 404. Sum of Left Leaves
    Leetcode 257. Binary Tree Paths
    Leetcode 235. Lowest Common Ancestor of a Binary Search Tree
    Leetcode 226. Invert Binary Tree
    Leetcode 112. Path Sum
    Leetcode 111. Minimum Depth of Binary Tree
  • 原文地址:https://www.cnblogs.com/Paranoid-LS/p/11332840.html
Copyright © 2011-2022 走看看