专题三 Problem L

2×n矩形铺砖问题
探讨2×n矩形使用1×2骨牌铺满的所有可能方案数量的计算方法,采用递推思想实现,解决数据溢出问题并提供AC代码。
一、题目编号:
          1012
二、简单题意:
         在2×n的一个长方形方格,用一个1× 2的骨牌铺满方格,输入n ,输出铺放方案的总数。
三、解题思路形成过程
         用v[i]表示2*i的方格一共有组成的方法数,i块方格就是I-1块方格再加一块。横着铺,如果前面i-1块方格已经铺好,则第I块方格只有一种铺法;竖着铺,前面i-2块方格已经铺好,也只有一种铺法。因此,v[i]=v[i-1]+v[i-2]。另外,我们易知v[1]=1;v[2]=2。
四、感想
         思路并不难想。跟上个题差不多,都是递推。但是第一遍提交后wa了,还是还需要考虑数据是否太大溢出的问题,改为long long类型就a了~
五、AC代码
#include<iostream>
using namespace std;
int main()
{
    long long v[52];
    v[1]=1;
    v[2]=2;
    int n;
    for(int i=3;i<52;i++)
    {
        v[i]=v[i-1]+v[i-2];
    }
    while(cin>>n)
    {
        cout<<v[n]<<endl;
    }
    return 0;
}

Dynamic programming is an algorithm suitable for solving the Knapsack problem. It avoids repeated calculations by decomposing complex problems into overlapping sub - problems and storing the solutions to the sub - problems. The core of dynamic programming is state definition and state transition equations [^1]. The general steps of using dynamic programming to solve the Knapsack problem are as follows: 1. **Define the state**: Usually, two - dimensional states are defined. For example, let `dp[i][j]` represent the maximum value that can be obtained when considering the first `i` items and the capacity of the knapsack is `j`. 2. **State transition equation**: For the 0 - 1 Knapsack problem, if the weight of the `i` - th item is `w[i]` and the value is `v[i]`, then the state transition equation is: - When `j < w[i]`, `dp[i][j]=dp[i - 1][j]` (the current item cannot be put into the knapsack). - When `j >= w[i]`, `dp[i][j]=max(dp[i - 1][j], dp[i - 1][j - w[i]]+v[i])` (choose whether to put the current item into the knapsack). Here is a simple Python code example for the 0 - 1 Knapsack problem: ```python def knapsack(weights, values, capacity): n = len(weights) dp = [[0 for _ in range(capacity + 1)] for _ in range(n + 1)] for i in range(1, n + 1): for j in range(1, capacity + 1): if j < weights[i - 1]: dp[i][j] = dp[i - 1][j] else: dp[i][j] = max(dp[i - 1][j], dp[i - 1][j - weights[i - 1]] + values[i - 1]) return dp[n][capacity] weights = [2, 3, 4, 5] values = [3, 4, 5, 6] capacity = 8 print(knapsack(weights, values, capacity)) ``` ### Application scenarios - **Resource allocation**: In project management, given a limited amount of resources (such as time, budget, manpower), and different tasks with different resource requirements and benefits, the Knapsack problem can be used to select the most profitable combination of tasks. - **Stock selection**: When an investor has a certain amount of funds and there are multiple stocks with different prices and expected returns, the Knapsack problem can be used to select the most profitable stock portfolio.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值