Technology Sharing

Bluebridge 7.11 dp

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

2. Weighing with weights - Lanqiao Cloud Course (lanqiao.cn)

Ideas

The core idea of ​​dynamic programming is to decompose the problem into smaller sub-problems and store the solutions of the sub-problems to avoid repeated calculations.

Arraysdp[i][j]Before useiThe weight that can be weighed isjquantity

The update process is as follows:

1. Initialization: dp[0][0] = 0;

2. For each weight wi:

 

ac code
  1. #include<bits/stdc++.h>
  2. typedef long long ll;
  3. #define IOS ios::sync_with_stdio(0),cin.tie(0),cout.tie(0)
  4. const ll M=2e5+10;
  5. const int N=110;
  6. int dp[N][M]={0};
  7. using namespace std;
  8. int main()
  9. {
  10. IOS;
  11. int n,num=0;
  12. cin>>n;
  13. int w[N];
  14. ll ans=0;
  15. for(int i=1;i<=n;i++)
  16. {
  17. cin>>w[i];
  18. num+=w[i];
  19. }
  20. dp[0][0]=1;
  21. for(int i=1;i<=n;i++)
  22. {
  23. for(int j=0;j<=num;j++)
  24. {
  25. dp[i][j] = dp[i-1][j] + dp[i-1][abs(j-w[i])] + dp[i-1][j+w[i]];
  26. //cout<<dp[i][j]<<" ";
  27. }
  28. //cout<<endl;
  29. }
  30. for(int i=1;i<=num;i++)
  31. {
  32. if(dp[n][i]) ans++;
  33. }
  34. cout<<ans;
  35. return 0;
  36. }