解题思路:
贪心,每次选择当前最长的木板即可。
AC代码:
//贪心 每次选择最长的木板
#include<iostream>
#include<stdio.h>
#include<queue>
#include<vector>
#include<functional>
using namespace std;
priority_queue<int> q;//大顶堆
int main() {
int l, n;
while (scanf("%d%d", &l, &n) != EOF) {
int len;
while (!q.empty())q.pop();
for (int i = 1; i <= n; i++) {
scanf("%d", &len);
q.push(len);
}
int now_len = 0, ans = 0;
while (!q.empty() && now_len < l) {
ans++;
now_len += q.top();
q.pop();
}
if (now_len >= l)cout << ans << endl;
else cout << "impossible" << endl;
}
return 0;
}

本文介绍了一个利用贪心算法解决木板拼接问题的编程实例。通过使用大顶堆数据结构,每次选取最长的木板进行拼接,直至达到目标长度或无法继续拼接。代码实现简洁高效,适用于类似问题的快速求解。

被折叠的 条评论
为什么被折叠?



