华为机试4.13
第三题,分糖果(参考网友的动态规划,C++)
/** -*- encoding: utf-8 -*- Version :1.0 */ #include <iostream> #include <vector> #include <algorithm> #include <set> using namespace std; int main() { int n; while (cin >> n) { vector<int> vec(n); int sum = 0; for (int i = 0; i < n; i++) { cin >> vec[i]; sum += vec[i]; } if (n < 2 || sum % 2 != 0) { cout << "-1" << endl; continue; } int target = sum / 2; vector<vector<bool>> dp(n + 1, vector<bool>(target + 1)); for (int i = 0; i <= n; i++) { dp[i][0] = true; } for (int i = 1; i <= n; i++) { for (int j = 1; j <= target; j++) { dp[i][j] = dp[i - 1][j]; if (!dp[i][j] && j >= vec[i - 1]) { dp[i][j] = dp[i - 1][j - vec[i - 1]]; } } } if (dp[n][target] == true) { cout << target << endl; set<int> st; while (target > 0) { for (int i = 0; i <= n; i++) { if (dp[i][target] == true) { st.insert(i - 1); target = target- vec[i - 1]; n = i - 1; break; } } } vector<int> a, b; for (int i = 0; i < vec.size(); i++) { if (st.find(i) != st.end()) { a.push_back(vec[i]); } else { b.push_back(vec[i]); } } for (int i = 0; i < a.size(); i++) { if (i == a.size() - 1) { cout << a[i] << endl; } else { cout << a[i] << " "; } } for (int i = 0; i < b.size(); i++) { if (i == b.size() - 1) { cout << b[i] << endl; } else { cout << b[i] << " "; } } } else { cout << "-1" << endl; } } return 0; }