POJ 3273 Monthly Expense(二分枚舉)

來源:互聯網
上載者:User

題目連結:http://poj.org/problem?id=3273

這個題目開始以為又是動態規劃什麼的,其實直接枚舉就可以做了,複雜度也很低

這個題目直接二分枚舉,找到滿足題目條件的最小值,不過這裡在枚舉的時候要判斷當前枚舉的值

是否滿足題目條件,這個用到一點點貪心演算法不過很簡單就是了,因為要連續的天數,所以就一直加

也就是前面的分組盡量在滿足條件的情況下盡量大就OK了,貪心的判斷每個枚舉條件是否符合,每次判斷

O(n)枚舉logn

O(n*logn)的演算法過這個題目還是比較輕鬆的!

/*3273*/#include <iostream>#include <string.h>#include <stdio.h>#include <algorithm>using namespace std;#define maxn 110000int rec[maxn];int n,m;bool is_ok(int num,int limit){    int i,p=0,ans=0;    for(i=0;i<n;i++)    {        if(ans+rec[i]<=limit)        ans+=rec[i];        else        {            p++;            if(p>=num)            return false;            ans=0;            i--;            if(i<0)            i=0;        }    }    if(ans>0)    p++;    if(p>num)    return false;    return true;}int find_ans(int l,int r,int day){    int mid,ans=1000000000;    while(l<=r)    {        mid=(l+r)>>1;        if(is_ok(day,mid))        {            //printf("ans:%d %d\n",mid,ans);            ans=(ans < mid ? ans : mid);            r=mid-1;        }        else        {            l=mid+1;        }    }    printf("%d\n",ans);    return 0;}int main(){    int i,MAX,sum;    while(scanf("%d%d",&n,&m)!=EOF)    {        MAX=0;        sum=0;        for(i=0;i<n;i++)            scanf("%d",&rec[i]);        find_ans(0,1000000000+1,m);       // printf("OK%d\n",is_ok(m,500));    }    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.