HDOJ 4268 Alice and Bob(贪心)

来源:互联网 发布:武威西安交大网络教育 编辑:程序博客网 时间:2024/06/05 17:40
/*第一次使用集合set这一类问题思路:对这2*n个元素进行排序,排序时候需要注意一点,如果h、w都相等时候,第二类需要排到前面。然后贪心,历遍所有元素,如果是第二类元素,进入集合;是第一类元素,则从堆中找出符合条件的w最大的元素,然后移除集合。推荐:③的使用*/#include <cstdio>#include <set>#include <iostream>using namespace std;const int nMax = 100007;int N;struct Node{int h, w;int type;Node(){}Node(int h, int w):h(h), w(w){}}node[nMax * 2];int cmp(const void *a, const void *b)//①{Node *pa = (Node *) a;Node *pb = (Node *) b;if(pa ->h != pb ->h)return pa ->h - pb ->h;else if(pa ->w != pb ->w)return pa ->w - pb ->w;elsereturn pb ->type - pa ->type;}multiset<int> _set;//③multiset<int>::iterator it;int main(){int T;scanf("%d", &T);while(T --){scanf("%d", &N);int i;int h, w;for(i = 0; i < 2 * N; ++ i){scanf("%d%d", &h, &w);node[i] = Node(h, w);}for(i = 0; i < N; ++ i)node[i].type = 1;for(; i < 2 * N; ++ i)node[i].type = 2;qsort(node, 2 * N, sizeof(node[0]), cmp);_set.clear();//③int ans = 0;for(i = 0; i < 2 * N; ++ i){if(node[i].type == 2)_set.insert(node[i].w);else{if(!_set.empty()){if(*_set.begin() <= node[i].w)//②{it = _set.upper_bound(node[i].w);-- it;ans ++;_set.erase(it);}}}}printf("%d\n", ans);}return 0;}