1. 程式人生 > >51nod 1672 區間交(貪心)

51nod 1672 區間交(貪心)

turn style 區間貪心 txt scan html emp ble line

http://www.51nod.com/onlineJudge/questionCode.html#!problemId=1672

題意:
技術分享

思路:
其實這就是一個經典的區間貪心問題,只需要按照左端點排序,然後用優先隊列維護,每次將右端點最小的點出隊列。

 1 #include<iostream>
 2 #include<algorithm>
 3 #include<cstring>
 4 #include<cstdio>
 5 #include<vector>
 6 #include<stack>
 7
#include<queue> 8 #include<cmath> 9 #include<map> 10 #include<set> 11 using namespace std; 12 typedef long long ll; 13 typedef pair<int,int> pll; 14 const int INF = 0x3f3f3f3f; 15 const int maxn = 100000+5; 16 17 int n,k,m; 18 int a[maxn]; 19 ll sum[maxn]; 20 21
priority_queue< int,vector<int>,greater<int> > q; 22 23 struct node 24 { 25 int left, right; 26 bool operator< (const node& rhs) const 27 { 28 return left<rhs.left||(left==rhs.left && right<rhs.right); 29 } 30 }p[maxn]; 31 32
int main() 33 { 34 //freopen("in.txt","r",stdin); 35 while(~scanf("%d%d%d",&n,&k,&m)) 36 { 37 sum[0]=0; 38 for(int i=1;i<=n;i++) 39 { 40 scanf("%d",&a[i]); 41 sum[i]=sum[i-1]+a[i]; 42 } 43 for(int i=0;i<m;i++) 44 scanf("%d%d",&p[i].left,&p[i].right); 45 sort(p,p+m); 46 while(!q.empty()) q.pop(); 47 ll ans=0; 48 for(int i=0;i<m;i++) 49 { 50 q.push(p[i].right); 51 if(q.size()==k) 52 { 53 ans=max(ans,sum[q.top()]-sum[p[i].left-1]); 54 q.pop(); 55 } 56 } 57 printf("%lld\n",ans); 58 } 59 return 0; 60 }

51nod 1672 區間交(貪心)