n个变量的线性方程的解的个数

时间:2018-03-06 05:57:31

标签: algorithm dynamic-programming

// A Dynamic programming based C++ program to find number of
// non-negative solutions for a given linear equation
#include<bits/stdc++.h>
using namespace std;

// Returns counr of solutions for given rhs and coefficients
// coeff[0..n-1]
int countSol(int coeff[], int n, int rhs)
{
    // Create and initialize a table to store results of
    // subproblems
    int dp[rhs+1];
    memset(dp, 0, sizeof(dp));
    dp[0] = 1;

    // Fill table in bottom up manner
    for (int i=0; i<n; i++)
      for (int j=coeff[i]; j<=rhs; j++)
         dp[j] += dp[j-coeff[i]];

    return dp[rhs];
}

// Driver program
int main()
{
    int coeff[]  = {2, 2, 5};
    int rhs = 4;
    int n = sizeof(coeff)/sizeof(coeff[0]);
    cout << countSol(coeff, n, rhs);
    return 0;
}

我是竞争性编程的新手,我只是偶然发现了这段代码。我想知道这个特定片段背后的直觉,比如第二个{​​{1}}循环如何帮助。谢谢。

for

这是采用自下而上的方法,而且 假设 // Fill table in bottom up manner for (int i=0; i<n; i++) for (int j=coeff[i]; j<=rhs; j++) dp[j] += dp[j-coeff[i]]; j= 3

那么j-coeff[i] = 2如何给出解决方案?如何简单地添加先前结果和当前结果可以得到线性变量的整体解?

1 个答案:

答案 0 :(得分:1)

想象一下,你有无限数量的金币价值2,3,5(你的coeff[]),你想知道一些解决方案的数量,以便给出一些总和形式的硬币。

在第一次循环运行中,您将用硬币填充表格2.表格将被填充

idx    0  1  2  3  4  5  6
num    1  0  1  0  1  0  1 

因为有唯一的方法来获得这些硬币的总和。

在第二轮循环中,你用硬币3填充表格 - 现在你将有可能由硬币2和3组成的总和

idx    0  1  2  3  4  5  6
num    1  0  1  1  1  1  2

请注意,单元格5填充2 + 3 - 类似于您的问题情况,单元格6现在包含2个变体:2 + 2 + 2和3 + 3

相关问题