hdu 5360 Hiking(優先隊列+貪心)
阿新 • • 發佈:2017-05-05
將不 cpp () tor 多少 int 實現 size pty
題目:http://acm.hdu.edu.cn/showproblem.php?
pid=5360
題意:beta有n個朋友,beta要邀請他的朋友go hiking,已知每一個朋友的理想人數[L,R](現有L~R個人準備去,那麽這個朋友就去)。
求最多有多少人去。
及beta邀請朋友的順序。
分析:每次邀請人的最優解就是:選會去的人裏面R最小的那個人。
代碼實現的話,cur代表已經準備go hiking的人數,每次將全部L<=cur的人放進優先隊列,選出R最小的那個。
假設隊列為空,那麽剩下的全部人將不會去,假設先出的那個人的[L,R]不滿足條件,那麽這個人以後也不會去go hiking,所以還是將他選出,僅僅是去go hiking的人數不增。
代碼:
#include <iostream> #include <cstdio> #include <cstring> #include <algorithm> #include <queue> using namespace std; const int maxn = 1e5+5; struct node { int L,R,id; bool operator < (const node &t) const { return R>t.R; } }s[maxn]; bool cmp(node a,node b) { if(a.L!=b.L) return a.L<b.L; return a.R<b.R; } int ans[maxn]; priority_queue <node > q; int main() { int ncase,n,i,j,cur,cnt; scanf("%d",&ncase); while(ncase--) { scanf("%d",&n); for(i=1;i<=n;i++) scanf("%d",&s[i].L); for(i=1;i<=n;i++) { scanf("%d",&s[i].R); s[i].id=i; } sort(s+1,s+1+n,cmp); cur=0; cnt=1; i=1; while(!q.empty()) q.pop(); while(1) { while(i<=n && s[i].L<=cur) q.push(s[i++]); if(q.empty()) break; node temp=q.top(); q.pop(); if(temp.L<=cur && temp.R>=cur) cur++; ans[cnt++]=temp.id; } for(;i<=n;i++) ans[cnt++]=s[i].id; printf("%d\n",cur); printf("%d",ans[1]); for(i=2;i<=n;i++) printf(" %d",ans[i]); printf("\n"); } return 0; }
hdu 5360 Hiking(優先隊列+貪心)