背包九问

  • 时间:
  • 浏览:
  • 来源:互联网

背包九问

acwing上的题解

1.01背包问题

二维数组+回溯选择

#include<iostream>
#include<algorithm>
using namespace std;
int n, m;
int w[10000];
int v[10000];
int dp[10000][10000];
void find(int n, int m);
int collect[10000];
int main() {
 cin >> n >> m;
 for (int i = 1; i <= n; i++)cin >> w[i] >> v[i];
 for (int i = 1; i <= n; i++) 
  for (int j = 0; j <= m; j++) {
   dp[i][j] = dp[i - 1][j];
   if (j >= w[i])
    dp[i][j] = max(dp[i][j], dp[i - 1][j - w[i]] + v[i]);
  }
 find(n,m);
 for (int i = 1; i <= n; i++)
  if (collect[i])cout << i << " ";
 cout << endl;
 cout << dp[n][m];
}
void find(int n,int m) {
 if (n) {
  if (dp[n][m] == dp[n - 1][m]) {
   find(n - 1, m);
  }else if (dp[n][m] == dp[n - 1][m - w[n]] + v[n]) {
   collect[n] = 1;
   find(n - 1, m - w[n]);
  }
 }
}

一维数组+collect回溯

题目详见柳婼的
https://www.liuchuo.net/archives/tag/动态规划

#include<iostream>
#include<algorithm>
#include<vector>
using namespace std;
int n, m;
int w[10000];
int v[10000];
int dp[10000];
int visit[10000][10000];
bool cmp(int x, int y) { return x > y; }
int main() {
 cin >> n >> m;
 for (int i = 1; i <= n; i++) {
  cin >> w[i];
  v[i] = w[i];
 }
 sort(v + 1, v + n + 1, cmp);
 sort(w + 1, w + n + 1, cmp);
 for (int i = 1; i <= n; i++)
  for (int j = m; j >= w[i]; j--)
   if (dp[j] <= dp[j - w[i]] + v[i]) {
    dp[j] = dp[j - w[i]] + v[i];
    visit[i][j] = 1;
   }
 vector<int>ve;
 int temp = m;
 if (dp[m] != m) {
  cout << "NO" << endl;
  return 0;
 }
 while (n) {
  if (visit[n][m]) {
   ve.push_back(n);
   m -= w[n];
  }
  n--;
 }
 for (int i = 0; i < ve.size(); i++)
  cout << w[ve[i]] << ' ';
 cout << endl;
}

完全背包问题

一维数组解决+回溯

#include<iostream>
#include<algorithm>
using namespace std;
int n, m;
int dp[10000];
int v[10000], w[10000];
int collect[10000][10000];
int visit[10000];
int main() {
 cin >> n >> m;
 for (int i = 1; i <= n; i++)cin >> w[i] >> v[i];
 for (int i = 1; i <= n; i++) 
  for(int j=w[i];j<=m;j++)
   if (dp[j] <= dp[j - w[i]] + v[i]) {
    dp[j] = dp[j - w[i]] + v[i];
    collect[i][j] = 1;
   }
 int temp = m;
 while (n) {
  if (collect[n][m]) {
   visit[n]++;
   m -= w[n];
  }else {
   n--;
  }
 }
 for (int i = 1; i <= temp; i++)
  cout << visit[i] << " ";
 cout << endl;
 cout << dp[temp] << endl;
}

二维数组+回溯

本文链接http://element-ui.cn/news/show-340101.aspx