1. 程式人生 > >[USACO 2009 Feb Gold] Fair Shuttle (貪心+優先隊列)

[USACO 2009 Feb Gold] Fair Shuttle (貪心+優先隊列)

esp 復雜度 {} pac ted 復雜 include 行程 define

題目大意:有N個站點的輕軌站,有一個容量為C的列車起點在1號站點,終點在N號站點,有K組牛群,每組數量為Mi(1≤Mi≤N),行程起點和終點分別為Si和Ei(1≤Si<Ei≤N)。計算最多有多少頭牛可以搭乘輕軌。

一道經典的貪心題目,每當一頭牛上車的時候,如果超載,我們就優先踢出去行程終點比較遠的那部分牛

而 踢出哪些行程終點較遠的牛 以及 哪些在車上的牛在這站到達了終點,都可以用優先隊列來維護,復雜度約為技術分享圖片

貼上代碼:

 1 #include <cstdio>
 2 #include <algorithm>
 3 #include <queue>
 4
#include <cstring> 5 #define N 50005 6 #define ll long long 7 using namespace std; 8 9 int k,n,c,ans; 10 int sum[N]; 11 struct COW{ 12 int x,y,w; 13 }cow[N]; 14 int cmp(COW s1,COW s2) {return s1.x<s2.x;} 15 struct node1{ 16 int id; 17 friend bool operator<(const node1 &s1,const
node1 &s2) 18 {return cow[s1.id].y > cow[s2.id].y;} 19 }; 20 node1 ins1(int idd){node1 w;w.id=idd;return w;} 21 struct node2{ 22 int id; 23 friend bool operator<(const node2 &s1,const node2 &s2) 24 {return cow[s1.id].y < cow[s2.id].y;} 25 }; 26 node2 ins2(int idd){node2 w;w.id=idd;return
w;} 27 int solve() 28 { 29 sort(cow+1,cow+k+1,cmp); 30 priority_queue<node1>q1; 31 priority_queue<node2>q2; 32 int j=1,cnt=0; 33 for(int i=1;i<=n;i++) 34 { 35 while(!q1.empty()) 36 { 37 node1 p=q1.top(); 38 if(cow[p.id].y==i) 39 { 40 q1.pop(); 41 ans+=sum[p.id]; 42 cnt-=sum[p.id]; 43 sum[p.id]=0; 44 }else{ 45 break; 46 } 47 } 48 while(cow[j].x==i) 49 { 50 q1.push(ins1(j)); 51 q2.push(ins2(j)); 52 cnt+=cow[j].w; 53 sum[j]=cow[j].w; 54 j++; 55 } 56 while(cnt>c) 57 { 58 node2 p=q2.top(); 59 if(cnt-sum[p.id]>c) 60 { 61 q2.pop(); 62 cnt-=sum[p.id]; 63 sum[p.id]=0; 64 }else{ 65 sum[p.id]-=(cnt-c); 66 cnt=c; 67 } 68 } 69 } 70 return ans; 71 } 72 73 int main() 74 { 75 scanf("%d%d%d",&k,&n,&c); 76 for(int i=1;i<=k;i++) scanf("%d%d%d",&cow[i].x,&cow[i].y,&cow[i].w); 77 printf("%d",solve()); 78 return 0; 79 }

[USACO 2009 Feb Gold] Fair Shuttle (貪心+優先隊列)