UVa Problem 103 - Stacking Boxes

本文探讨了UVaProblem103中的StackingBoxes问题,通过求解最长上升子序列来解决箱子堆叠问题。详细介绍了算法实现过程,包括结构体定义、序列化递归输出以及使用动态规划优化查找最长上升子序列。代码实例展示了如何在限制条件下高效地处理问题。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

// UVa Problem 103 - Stacking Boxes // Verdict: Accepted // Submission Date: 2011-10-17 // UVa Run Time: 0.012s // // 版权所有(C)2011,邱秋。metaphysis # yeah dot net // // [解题方法] // 该问题可以归结为求最长上升子序列的问题。 #include <algorithm> #include <iostream> using namespace std; #define MAXD 10 #define MAXN 30 #define END (-1) struct box { public: int dimensionality[MAXD]; int dimensions; int index; bool operator<(const box &other) const { for (int i = 0; i < dimensions; i++) if (dimensionality[i] != other.dimensionality[i]) return dimensionality[i] < other.dimensionality[i]; return false; } bool nests(const box &other) const { for (int i = 0; i < dimensions; i++) if (dimensionality[i] >= other.dimensionality[i]) return false; return true; } }; box boxes[MAXN]; int longest[MAXN]; int ancestor[MAXN]; int nBoxes, nDimensions; void sequences(int current) { if (ancestor[current] != END) sequences(ancestor[current]); cout << (ancestor[current] == END ? "" : " ") << (boxes[current].index + 1); } void lis(void) { for (int i = 0; i < nBoxes; i++) for (int j = 0; j < i; j++) if (boxes[j].nests(boxes[i]) && (longest[j] + 1) > longest[i]) { longest[i] = longest[j] + 1; ancestor[i] = j; } int maximum = 0, marker; for (int i = 0; i < nBoxes; i++) if (maximum < longest[i]) { maximum = longest[i]; marker = i; } cout << maximum << endl; sequences(marker); cout << endl; } int main(int ac, char *av[]) { while (cin >> nBoxes >> nDimensions) { for (int i = 0; i < nBoxes; i++) { longest[i] = 1; ancestor[i] = END; boxes[i].dimensions = nDimensions; boxes[i].index = i; for (int j = 0; j < nDimensions; j++) cin >> boxes[i].dimensionality[j]; sort(boxes[i].dimensionality, boxes[i].dimensionality + nDimensions); } sort(boxes, boxes + nBoxes); lis(); } return 0; }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值