一维数组

一维,二维,三维数组,vector 初始化

自闭症网瘾萝莉.ら 提交于 2019-11-26 19:44:27
1. 用memset初始化数组: 1)按照字节赋值 2)头文件在<cstring>中 注:由于memset函数是按照字节赋值的,所以对int型数组用该函数时,只能是0或-1,否则会出错,这里,不管数组是多少维的,语法均为: int dp[84][84][84][2]; memset(dp, 0, sizeof(dp)); //只能赋值0或-1 2. fill 初始化vector和数组: 1)按照变量类型单元赋值,将区间 [first, end) 中的每个单元都赋为同一个值。 2)头文件在<algorithm>中 // fill algorithm example #include <iostream> // std::cout #include <algorithm> // std::fill #include <vector> // std::vector int main () { std::vector<int> myvector (8); // myvector: 0 0 0 0 0 0 0 0 std::fill (myvector.begin(),myvector.begin()+4,5); // myvector: 5 5 5 5 0 0 0 0 std::fill (myvector.begin()+3,myvector.end()-2,8); //

动态规划之背包问题

白昼怎懂夜的黑 提交于 2019-11-26 19:24:41
动态规划之背包问题 01背包问题 问题1 为什么01背包问题可以用一维数组来优化? 问题2 使用一维数组优化过程中为什么物体的重量要从大到小枚举? code1 code2 code3 code(一维数组优化) 01背包问题 问题1 为什么01背包问题可以用一维数组来优化? 用二维数组枚举如下: 所以在枚举过程中仅用到上一行的数据,所以可以用一维数组来优化。 问题2 使用一维数组优化过程中为什么物体的重量要从大到小枚举? 我从大到小枚举如下: 我从小到大枚举如下: code1 #include<iostream> #define N 6 #define W 21 int B[N][W] = { 0 }; int w[6] = { 0, 2, 3, 4, 5, 9 }; int v[6] = { 0, 3, 4, 5, 8, 10 }; void knapsack() { int k, C; for (k = 1; k < N; k++) { for (C = 1; C < W; C++) { if (w[k] > C) { B[k][C] = B[k - 1][C]; } else { int value1 = B[k - 1][C - w[k]] + v[k]; int value2 = B[k - 1][C]; if (value1 > value2) { B[k][C] =