[BZOJ1029] [JSOI2007]建築搶修(貪心 + 優先隊列)

來源:互聯網
上載者:User

標籤:open   can   目前時間   top   onclick   online   algo   priority   技術   

傳送門

 

把資料存在結構體中,至於怎麼貪心?

肯定會有些想法,正確錯誤先不必說,先來試一試。

1.按照 t2 為第一關鍵字從小到大排,按照 t1 為第二關鍵字從小到大排

  這個顯然錯,比如後面有個數的 t1 比前面小,t2 比前面大,顯然用這個代替前面的更優

2.按照 t1 為第一關鍵字從小到大排,按照 t2 為第二關鍵字從小到大排

  這個也是錯的,比如

  4

  1 1

  1 5

  3 4

  4 5

  按照這個貪心是 2,實際應該是 3

 

至於正確貪心,如果 目前時間 + t1[i] <= t2[i],說明可以建完,ans++,並把 t1 放入大根堆

       如果 目前時間 + t1[i] > t2[i],說明不能建,那麼把當前的 t1[i] 和堆頂比較

         如果 > 堆頂,continue

         如果 < 堆頂,如果 目前時間 - 堆頂 + t1[i] <= t2[i],說明拿它替換堆頂更優,那麼就替換,ans++

 

 1 #include <cstdio> 2 #include <queue> 3 #include <algorithm> 4  5 int n, time, ans; 6 struct node 7 { 8     int a, b; 9 }p[150001];10 std::priority_queue <int> q;11 12 inline bool cmp(node x, node y)13 {14     return x.b < y.b;15 }16 17 int main()18 {19     int i;20     scanf("%d", &n);21     for(i = 1; i <= n; i++) scanf("%d %d", &p[i].a, &p[i].b);22     std::sort(p + 1, p + n + 1, cmp);23     for(i = 1; i <= n; i++)24     {25         if(time + p[i].a <= p[i].b)26         {27             time += p[i].a;28             ans++;29             q.push(p[i].a);30         }31         else if(p[i].a < q.top())32         {33             if(time - q.top() + p[i].a <= p[i].b)34             {35                 time = time - q.top() + p[i].a;36                 q.pop();37                 q.push(p[i].a);38             }39         }40     }41     printf("%d", ans);42     return 0;43 }
View Code

 我真是菜啊,錯誤的貪心都舉不出來反例,只有對拍出來。

[BZOJ1029] [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.