您的位置:首页 > 其它

《Cracking the Coding Interview》——第11章:排序和搜索——题目7

2014-03-21 22:18 513 查看
2014-03-21 22:05

题目:给你N个盒子堆成一座塔,要求下面盒子的长和宽都要严格大于上面的。问最多能堆多少个盒子?

解法1:O(n^2)的动态规划解决。其实是最长递增子序列问题,所以也可以用O(n * log(n))的优化算法。

代码:

// 11.7 n boxes are to stack up to a tower. Every box must be strictly smaller in width and height than the one right below it.
// How many boxes at most can you stack up?
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

struct Box {
int x;
int y;
Box(int _x = 0, int _y = 0): x(_x), y(_y) {};

bool operator < (const Box &other) {
if (x != other.x) {
return x < other.x;
} else {
return y < other.y;
}
};
};

int main()
{
vector<Box> v;
vector<int> dp;
int n;
int i, j;
int res;

while (scanf("%d", &n) == 1 && n > 0) {
v.resize(n);
for (i = 0; i < n; ++i) {
scanf("%d%d", &v[i].x, &v[i].y);
}
sort(v.begin(), v.end());
dp.resize(n);
res = 0;
for (i = 0; i < n; ++i) {
dp[i] = 1;
for (j = 0; j < i; ++j) {
if (v[j].x < v[i].x && v[j].y < v[i].y) {
dp[i] = dp[j] + 1 > dp[i] ? dp[j] + 1 : dp[i];
}
}
res = dp[i] > res ? dp[i] : res;
}
printf("%d\n", res);

v.clear();
dp.clear();
}

return 0;
}


解法2:用二分查找优化后的代码,其中使用了STL算法库提供的lower_bound(),二分也不总是要手写的。

代码:

// 11.7 n boxes are to stack up to a tower. Every box must be strictly smaller in width and height than the one right below it.
// How many boxes at most can you stack up?
#include <algorithm>
#include <cstdio>
#include <vector>
using namespace std;

struct Box {
int x;
int y;
Box(int _x = 0, int _y = 0): x(_x), y(_y) {};

bool operator < (const Box &other) {
if (x != other.x) {
return x < other.x;
} else {
return y < other.y;
}
};
};

int main()
{
vector<Box> v;
vector<int> dp;
vector<int>::iterator it;
int n;
int i;

while (scanf("%d", &n) == 1 && n > 0) {
v.resize(n);
for (i = 0; i < n; ++i) {
scanf("%d%d", &v[i].x, &v[i].y);
}
sort(v.begin(), v.end());
dp.push_back(v[0].y);
for (i = 1; i < n; ++i) {
if (v[i].y > dp[dp.size() - 1]) {
dp.push_back(v[i].y);
} else {
it = lower_bound(dp.begin(), dp.end(), v[i].y);
*it = v[i].y;
}
}
printf("%d\n", (int)dp.size());

v.clear();
dp.clear();
}

return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: 
相关文章推荐