Question link: http://acm.hdu.edu.cn/showproblem.php? PID = 1, 4268
Generally, for a question like this, we will first think of a dynamic planning algorithm. But when we look at the data, we will definitely think of an algorithm for finding an O (n) or O (N * logn, so Dynamic Planning
Algorithms are hard to find, and this low-complexity dynamic planning algorithm is rarely seen, so it can only be greedy to provide this complexity.
Put the cards of two people together, make a mark of Alice or Bob, and then sort by length, appearance, etc. by width, are equal, Alice is behind Bob in front
Then traverse from the front to the back. If it is Bob, insert Bob's width into the set directly. If it is Alice, let Alice's card overwrite the width of the set than Alice's.
If the width is small or equal, the maximum width is deleted from the set. Here, why can we overwrite the width that meets the conditions? Because the preceding values are sorted in ascending order, this
Is a very obvious greedy!
#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>#include <set>using namespace std;#define maxn 110000struct point{ int length; int width; int first;}po[maxn*2];int n;multiset<int> my_set;bool cmp(const point &a,const point &b){ if(a.length == b.length) { if(a.width == b.width) return a.first < b.first; return a.width < b.width; } return a.length < b.length;}multiset<int>::iterator it;int find_ans(){ int ans=0,i,j,k; for(i=0;i<n;i++) { if(po[i].first==0) my_set.insert(po[i].width); else { if(!my_set.empty() && *my_set.begin() <= po[i].width) { it=my_set.upper_bound(po[i].width); it--; my_set.erase(it); ans++; } } } return ans;}int main(){ int t,i,j,k; scanf("%d",&t); while(t--) { my_set.clear(); scanf("%d",&n); for(i=0;i<n;i++) { scanf("%d%d",&po[i].length,&po[i].width); po[i].first=1; } n*=2; for(i;i<n;i++) { scanf("%d%d",&po[i].length,&po[i].width); po[i].first=0; } sort(po,po+n,cmp); printf("%d\n",find_ans()); } return 0;}