本文主要是介绍信封嵌套,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题意:
给定N个信封的长度和宽度如果一个信封的长和宽都分别小于另一个信封的长和宽,则这个信封可以放入另一个信封问最多嵌套多少个信封
例子 :
输入: [[5, 4], [6, 4], [6, 7], [2, 3]]
输出 : 3 ([2, 3] = > [5, 4] = > [6, 7]) ,
分析:首先按照信封的长度排序,然后当前i个信封的长度跟宽度都小于j个时,取较大值
#include <iostream>
#include <vector>
#include <algorithm>using namespace std;
bool compare(pair<int, int> buf1, pair<int, int> buf2)
{if (buf1.first == buf2.first)return buf1.second < buf2.second;elsereturn buf1.first < buf2.first;
}int main()
{int n;cin >> n;vector<pair<int, int>> envelope(n);vector<int> dp(n);for (int i = 0; i < n; ++i){cin >> envelope[i].first >> envelope[i].second;}sort(envelope.begin(), envelope.end(), compare);for (int i = 0; i < n; ++i){dp[i] = 1;for (int j = 0; j < i; ++j){if (envelope[i].first > envelope[j].first && envelope[i].second > envelope[j].second)dp[i] = max(dp[i], dp[j] + 1);}}cout << *max_element(dp.begin(), dp.end()) << endl;
}
这篇关于信封嵌套的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!