Codeforces Round #422 (Div. 2) C. Hacker, pack your bags! 排序+貪心

來源:互聯網
上載者:User

標籤:blog   class   不能   http   多少   nbsp   row   pre   題解   

連結:

http://codeforces.com/contest/822/problem/C

題意:

有x天的假期, 有n張旅行票, 每張票有起始時間l, 結束時間r, 花費cost, 想把假期分成兩部分出去旅遊, 兩部分時間不能重合(ri < lj || rj < li), 問最小花費是多少, 如果不能兩部分, 輸出-1

題解:

CF官方解法, 效率O(nlogn2) 
設定一個結構體, struct P{int p, len, cost, type}; 
將每張票(l, r, cost) 表示成兩個結構體, P(l, r-l+1, cost, -1), P(r, r-l+1, cost, 1); 
設定一個數組best[i], 表示時間長度為i的最便宜的票, 一開始全為INF, 之後邊用邊更新 
將結構體數字排序, 首先按p排序, p相同按type排序, 這樣保證了是按時間順序且同樣時間type為-1的在type為1的前面 
遍曆整個結構體數組 
type為1, 則用p[i].cost更新best[p[i].len] 
type為-1, 則用p[i].cost+best[x-p[i].len]更新ans 
因為數組按照p然後type排序, 保證了更新ans是用到的best[], 裡面儲存的都是根據時間段在之前的票得出的, 保證時間不會重疊

代碼:
 1 #include <bits/stdc++.h> 2  3 using namespace std; 4 typedef long long ll; 5 const int MAXN = 2E5 + 100, INF = 2e9+10; 6 int n, x, l, r, c; 7 int best[MAXN]; 8 struct P 9 {10     int p, len, cost, type;11     bool operator<(const P &x)12     {13         if(p == x.p) return type < x.type;14         return p < x.p;15     }16 }p[MAXN*2];17 18 19 int main()20 {21     scanf("%d%d", &n, &x);22     int cnt = 0;23     for(int i=0; i<n; ++i)24     {25         scanf("%d%d%d", &l, &r, &c);26         p[cnt++] = P{l, r-l+1, c, -1};27         p[cnt++] = P{r, r-l+1, c, 1};28     }29     ll ans = INF;30     sort(p, p+cnt);31     fill(best, best+x, INF);32 33     for(int i=0; i<cnt; ++i)34     {35         if(p[i].type == -1)36         {37             if(p[i].len < x)38             {39                 ans = min(ans, (ll)p[i].cost+(ll)best[x-p[i].len]);40             }41         }42         else best[p[i].len] = min(best[p[i].len], p[i].cost);43     }44 45     if(ans >= INF) ans = -1;46     cout << ans <<endl;47 48     return 0;49 }

 

Codeforces Round #422 (Div. 2) C. Hacker, pack your bags! 排序+貪心

聯繫我們

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