HDU 4268 Alice and Bob(貪心)

來源:互聯網
上載者:User

題目連結:http://acm.hdu.edu.cn/showproblem.php?pid=4268

一般像這種題目,首先會想到動態規划算法但是這個題目一看資料就想到肯定是要找一個O(n)的或者O(n*logn)的一個演算法,所以動態規劃這種

演算法比較難找,也很少見這種低複雜度的動態規划算法,所以就只能是貪心能提供這種複雜度了。

把兩個人的牌揉到一起,做個標記是alice的還是bob的,然後按照長排序,長相等按照寬排序,都相等就alice在後bob在前面

然後從前向後遍曆,如果是bob的,直接將bob的寬插入的set中,如果是alice,則讓alice的這張牌去覆蓋set裡面比alice的寬

小或相等的最大的寬,然後從set中刪除,這裡為什麼寬符合條件就能覆蓋呢,因為前面按照長從小到大排序了,所以說這個

是一個很明顯的貪心!

#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;}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.