本文共 1660 字,大约阅读时间需要 5 分钟。
George曾经拥有若干根长度相同的木棍,将它们随机切割,直到所有部分的长度都不超过50个单位。现在他想恢复原来的状态,但忘记了原来的棍子数量和每根原来的长度。你的任务是帮助他设计一个程序,计算最小的可能原长。
输入文件包含多个部分:
输出文件中应包含一行,表示最小的可能原长。
9 5 2 1 5 2 1 5 2 1 4 1 2 3 4 0
6 5
这个问题可以通过动态规划来解决。我们需要将切割后的木棍重新组合成若干根长度相同的木棍。为了找到最小的原长,我们可以从最长的可能长度开始尝试。
具体步骤如下:
#include#include #include #include using namespace std;struct stick { int length, mark;};stick sti[70];bool cmp(stick x, stick y) { return x.length > y.length;}int dfs(int cnt, int now, int id) { if (cnt == num) return 1; for (int i = id; i < num; i++) { if (sti[i].length <= now) { if (dfs(cnt + 1, now + sti[i].length, i)) { return 1; } } } return 0;}int main() { int n, num, len, sum; stick sti[70]; for (int i = 0; i < 70; i++) { sti[i].mark = -1; } while (true) { scanf("%d %d", &n, &num); vector parts(n, 0); for (int i = 0; i < n; i++) { parts[i] = sti[i].mark; } sort(sti, sti + num, cmp); int ret = dfs(0, 0, 0); if (!ret) { puts("0"); } else { puts(to_string(len)); } scanf("%d", &break_flag); if (break_flag == 0) break; } return 0;}
stick结构体用于存储每根木棍的长度和标记。通过这种方法,我们可以高效地找到最小的原长,满足题目要求。
转载地址:http://kzhfk.baihongyu.com/