TA的每日心情![](source/plugin/dsu_paulsign/img/emot/kx.gif) | 开心 2024-8-31 15:58 |
---|
签到天数: 89 天 [LV.6]常住居民II
管理员
- 积分
- 3366
|
使用贪心算法的简单C++代码示例,用于解决一维套料问题
- #include <iostream>
- #include <vector>
- #include <algorithm>
- using namespace std;
- vector<int> stockCutting(vector<int> lengths, int stockLength) {
- sort(lengths.begin(), lengths.end(), greater<int>());
- vector<int> result;
- while (!lengths.empty()) {
- int currentLength = lengths[0];
- int count = stockLength / currentLength;
- result.push_back(count);
- for (int i = 0; i < count; ++i) {
- lengths.erase(remove(lengths.begin(), lengths.end(), currentLength), lengths.end());
- }
- sort(lengths.begin(), lengths.end(), greater<int>());
- }
- return result;
- }
- int main() {
- vector<int> lengths = {1, 2, 3, 4, 5, 6, 7, 8};
- int stockLength = 10;
- vector<int> result = stockCutting(lengths, stockLength);
- for (int i : result) {
- cout << i << " ";
- }
- return 0;
- }
复制代码 |
|