BZOJ 1029 JSOI2007 建築搶修 貪心+堆

來源:互聯網
上載者:User

標籤:排序   include   for   code   UI   operator   cpp   維護   define   

題目大意:n個建築須要搶修。第i個建築須要T1時間搶修。必須在T2時間之前搶修完成。求最多能搶修多少建築

首先我們對T2排序 然後依次修理 可是這樣貪心顯然是不對的 比方說這組資料:

5
10 10
10 20
2 21
2 21
2 21

貪心僅僅能修理前兩個。而實際上最多能夠修理4個

於是我們考慮修正貪心演算法

比方說這組資料,當我們枚舉到3的時候。儘管已經無法修理很多其它了,可是我們能夠取消修理建築1而改修理3。這樣儘管不能更新ans 可是能夠為後面的建築節省時間

所以做法就非常明白了

我們維護一個大根堆 每修理一棟建築 我們就把這棟建築的T1值增加堆 若當前無法修理 我們推斷堆頂是否比這棟建築的T1大 假設大 取消修理堆頂。改為修理當前建築

#include<cstdio>#include<cstring>#include<iostream>#include<algorithm>#define M 150100using namespace std;struct construction{int T1,T2;bool operator < (const construction &x) const{return T2 < x.T2;}}buildings[M];int n,ans,now,heap[M],top;void Insert(int x){heap[++top]=x;int t=top;while(t>1&&heap[t]>heap[t>>1])swap(heap[t],heap[t>>1]),t>>=1;}void Pop(){heap[1]=heap[top--];int t=2;while(t<=top){if(t<top&&heap[t+1]>heap[t])++t;if(heap[t]>heap[t>>1])swap(heap[t],heap[t>>1]),t<<=1;elsebreak;}}int main(){int i;cin>>n;for(i=1;i<=n;i++)scanf("%d%d",&buildings[i].T1,&buildings[i].T2);sort(buildings+1,buildings+n+1);for(i=1;i<=n;i++){if(now+buildings[i].T1<=buildings[i].T2){now+=buildings[i].T1;++ans;Insert(buildings[i].T1);}else{if(!top)continue;int temp=heap[1];if( temp>buildings[i].T1 )now=now+buildings[i].T1-temp,Pop(),Insert(buildings[i].T1);}}cout<<ans<<endl;}


BZOJ 1029 JSOI2007 建築搶修 貪心+堆

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.