USACO A Rectangular Barn 解题报告

来源:互联网 发布:程序员客栈怎么接单 编辑:程序博客网 时间:2024/06/04 04:01

这道题是leetcode上面的题,有个非常聪明的解法:http://www.cnblogs.com/lichen782/p/leetcode_maximal_rectangle.html。总体的时间复杂度是O(RC)。但是提交了3次才通过。原因是没有完全记住原解法的原理:以每个柱子为要形成的矩形的高,左边第一个比其低的柱子为栈里面左边那个(做高的柱子已经出栈,所以左边那个柱子就是栈顶的元素),右边第一个比其低的矩形就是当前这个柱子,这样才能正确算出左右边界。

第2次错误是因为大小超过了限制,所以不能存储整个barn。这里的做法是只存储损坏的矩形坐标。

USER: chen chen [thestor1]TASK: rectbarnLANG: C++Compiling...Compile: OKExecuting...   Test 1: TEST OK [0.011 secs, 3504 KB]   Test 2: TEST OK [0.008 secs, 3504 KB]   Test 3: TEST OK [0.005 secs, 3504 KB]   Test 4: TEST OK [0.035 secs, 3636 KB]   Test 5: TEST OK [0.016 secs, 3504 KB]   Test 6: TEST OK [0.049 secs, 3636 KB]   Test 7: TEST OK [0.062 secs, 3768 KB]   Test 8: TEST OK [0.292 secs, 4144 KB]   Test 9: TEST OK [0.429 secs, 3504 KB]   Test 10: TEST OK [0.443 secs, 3504 KB]All tests OK.


/* ID: thestor1 LANG: C++ TASK: rectbarn */#include <iostream>#include <fstream>#include <cmath>#include <cstdio>#include <cstring>#include <climits>#include <cassert>#include <string>#include <vector>#include <list>#include <set>#include <map>#include <queue>#include <stack>#include <algorithm>#include <cassert>using namespace std;int main(){ifstream fin("rectbarn.in");int R, C, P;fin >> R >> C >> P;// vector<vector<int> > barn(R, vector<int>(C, 1));std::vector<set<int> > damage(R, set<int>());for (int i = 0; i < P; ++i){int r, c;fin >> r >> c;// barn[r - 1][c - 1] = 0;damage[r - 1].insert(c - 1);}fin.close();int maxarea = 0, area;vector<int> height(C, 0);stack<int> st;for (int r = 0; r < R; ++r){for (int c = 0; c < C; ++c){// if (barn[r][c] == 0)if (damage[r].find(c) != damage[r].end()){height[c] = 0;}else{height[c]++;}}for (int c = 0; c < C; ++c){if (st.empty() || height[c] >= height[st.top()]){st.push(c);}else{while (!st.empty() && height[st.top()] > height[c]){int h = height[st.top()];st.pop();area = h * (st.empty() ? c : c - st.top() - 1);if (area > maxarea){maxarea = area;}}st.push(c);}}while (!st.empty()){int l = st.top();int h = height[l];st.pop();area = h * (st.empty() ? C : C - st.top() - 1);if (area > maxarea){maxarea = area;}}}ofstream fout("rectbarn.out");fout << maxarea << endl;fout.close();return 0;  }


0 0
原创粉丝点击