LeetCode DP篇-背包问题(416、518)】的更多相关文章

问题一:01背包 题目: [题目描述] 一个旅行者有一个最多能装 M 公斤的背包,现在有 n件物品,它们的重量分别是W1,W2,...,Wn它们的价值分别为C1,C2,...,Cn求旅行者能获得最大总价值. [输入] 第一行:两个整数,MM(背包容量,M≤200)和NN(物品数量,N≤30): 第2..N+12..N+1行:每行二个整数Wi,CiWi,Ci,表示每个物品的重量和价值. [输出] 仅一行,一个数,表示最大总价值. [输入样例] 10 4 2 1 3 3 4 5 7 9 [输出样例]…
1.先放上0-1背包模板 二维数组 for(int i=1;i<=n;i++)//枚举 物品 for(int j=1;j<=V;j++)//枚举体积 //这个位置是可以正序枚举的. qwq //一维01背包必须倒叙 emmm //这个没错a emmm if(j>=c[i]) f[i][j]=max(f[i-1][j],f[i-1][j-c[i]]+w[i]);//状态转移方程. else f[i][j]=f[i-1][j]. 滚动二维数组 int dp[2][10010]; int ro…
题目链接:http://poj.org/problem?id=3624 1.p[i][j]表示,背包容量为j,从i,i+1,i+2,...,n的最优解. 2.递推公式 p[i][j]=max(p[i+1][j],p[i+1][j-w[i]]+v[i]); #include <stdio.h> #include <algorithm> #include <string.h> #define NUM 3410 //物品数量的上限 #define CAP 1300 //背包容…
题目链接:http://codeforces.com/problemset/problem/148/E E. Porcelain time limit per test 1 second memory limit per test 256 megabytes input standard input output standard output During her tantrums the princess usually smashes some collectable porcelain.…
https://leetcode.com/problems/k-inverse-pairs-array/description/ [题意] 给定n和k,求正好有k个逆序对的长度为n的序列有多少个,0<=k<=1000, 1<=n<=1000,答案模1e9+7 [思路] dp[i][j]表示正好有j个逆序对的长度为i的序列的方案数,最终我们要求的就是dp[n][k] 考虑dp[i+1][j]和dp[i][j]的关系,长度为i+1的序列相当于在长度为i的序列中插入一个数,那么有 xxx…
https://leetcode.com/problems/palindrome-partitioning-ii/description/ [题意] 给定一个字符串,求最少切割多少下,使得切割后的每个子串都是回文串 [思路] 求一个字符串的所有子串是否是回文串,O(n^2) dp从后往前推 vector<vector<bool> > p(len,vector<bool>(len)); ;i<len-;i++){ ;j<len-;j++){ if(j!=i)…
https://leetcode.com/problems/dungeon-game/description/ [题意] 给定m*n的地牢,王子初始位置在左上角,公主在右下角不动,王子要去救公主,每步只能往右或往下走一格.每个格子是一个整数,负数代表生命值减掉相应分数,正数表示生命值增加相应分值,要保证王子在走的过程中不挂掉,即经过每个格子后的生命值大于等于1,问王子最初的生命值最少是多少. [思路] 倒着推dp,计算(i,j)->(m,n)的可生存血量. dp[i][j]=max(1,min(…
我又被虐了... A. 最长不下降子序列 考场打的错解,成功调了两个半小时还是没A, 事实上和正解的思路很近了,只是没有想到直接将前$D$个及后$D$个直接提出来 确实当时思路有些紊乱,打的时候只是将前两个及后两个循环节提出来, 因为该题中$D$的范围很小,因此最长公共子序列中最多只有$D$个不同的数 所以我们可以想到中间的一段相同的数一定是可以移成中间的一段数,本质是一样的 B. 完全背包问题 没想到是到图论题啊啊 考虑到$w$的范围很大,然而$v$的范围很小,于是我们开始转化原来的$DP$方…
Best Time to Buy and Sell Stock 题目: Say you have an array for which the ith element is the price of a given stock on day i. If you were only permitted to complete at most one transaction (ie, buy one and sell one share of the stock), design an algori…
You are given a list of non-negative integers, a1, a2, ..., an, and a target, S. Now you have 2 symbols + and -. For each integer, you should choose one from + and - as its new symbol. Find out how many ways to assign symbols to make sum of integers…