标签:因此 否则 set produce ecif john number too call
Farmer John has N cows that need to be milked (1 <= N <= 10,000), each of which takes only one unit of time to milk.
Being impatient animals, some cows will refuse to be milked if Farmer John waits too long to milk them. More specifically, cow i produces g_i gallons of milk (1 <= g_i <= 1000), but only if she is milked before a deadline at time d_i (1 <= d_i <= 10,000). Time starts at t=0, so at most x total cows can be milked prior to a deadline at time t=x.
Please help Farmer John determine the maximum amount of milk that he can obtain if he milks the cows optimally.
FJ有N(1 <= N <= 10,000)头牛要挤牛奶,每头牛需要花费1单位时间。
奶牛很厌烦等待,奶牛i在它的截止时间d_i (1 <= d_i <= 10,000)前挤g(1 <= g_i <= 1000)的奶,否则将不能挤奶。时间t开始时为0,即在时间t=x时,最多可以挤x头奶牛。
请计算FJ的最大挤奶量。
* Line 1: The value of N.
* Lines 2..1+N: Line i+1 contains the integers g_i and d_i.
输出格式:* Line 1: The maximum number of gallons of milk Farmer John can obtain.
There are 4 cows. The first produces 10 gallons of milk if milked by time 3, and so on.
Farmer John milks cow 3 first, giving up on cow 4 since she cannot be milked by her deadline due to the conflict with cow 3. Farmer John then milks cows 1 and 2.
楼下STL的nlogn做法也很巧妙啊
这里说一下O(n)的单调队列做法
首先每个元素肯定要按照位置排序,然后依次进队,判断如果队尾的数大小小于要进队的数,那就把队尾弹出,直到队尾的数大于等于要进队的数
这是为了维护单调性
然后再判断如果队头的数位置的差值大于d,出队,直到差值小于d,此时队头的数为单调队列内的合法最大值
因此只要将要进队的数与目前的队头元素比较即可
这样维护了前面的,后面的反一下就好了
时间复杂度:因为每个元素最多进队出队一次,所以是O(n)的
单调队列有单向性,这个题对两边都有要求,所以要正反向跑两次。
1 #include<bits/stdc++.h> 2 using namespace std; 3 struct ppap{ 4 int x,y; 5 }a[100001]; 6 ppap qq[100001]; 7 bool q[100001],h[100001]; 8 inline bool cmp(ppap a,ppap b){return a.x<b.x;} 9 int main() 10 { 11 int n,d;scanf("%d%d",&n,&d); 12 for(int i=1;i<=n;i++)scanf("%d%d",&a[i].x,&a[i].y); 13 sort(a+1,a+n+1,cmp); 14 int l=1,r=0; 15 for(int i=1;i<=n;i++){ 16 while(l<=r&&qq[r].y<a[i].y)r--; 17 qq[++r]=a[i]; 18 while(l<=r&&qq[l].x<a[i].x-d)l++; 19 if(qq[l].y>=a[i].y*2)q[i]=1; 20 } 21 memset(qq,0,sizeof qq);l=1;r=0; 22 for(int i=n;i;i--){ 23 while(l<=r&&qq[r].y<a[i].y)r--; 24 qq[++r]=a[i]; 25 while(l<=r&&qq[l].x>a[i].x+d)l++; 26 if(qq[l].y>=a[i].y*2)h[i]=1; 27 } 28 int ans=0; 29 for(int i=1;i<=n;i++)if(q[i]&&h[i])ans++; 30 printf("%d",ans); 31 return 0; 32 }
P3088 [USACO13NOV]挤奶牛Crowded Cows(单调队列)
标签:因此 否则 set produce ecif john number too call
原文地址:https://www.cnblogs.com/zhangbuang/p/10284364.html