Maintain an incrementing and descending monotone queue
AssignmentTime
limit:4000/2000 MS (java/others) Memory limit:65536/65536 K (java/others)
Total submission (s): Accepted submission (s): 40
Problem Descriptiontom owns a company and he's the boss. There is n staffs which is numbered from 1 to N in the this company, and every the staff have a ability. Now, Tom was going to assign a special task to some staffs who were in the same group. In a group, the difference of the ability for any of the. than K, and their numbers are continuous. Tom want to know the number of groups like this.
Inputin the first line a number T indicates the number of test cases. Then for each case the first line contain 2 numbers n, K (1<=n<=100000, 0<k<=10^9), indicate the company have n Persons, k means the maximum difference between abilities of the staff in a group are less than K. The second line contains n integers:a[1],a[2],..., A[n] (0<=a[i]<=10^9), indicate the i-th staff ' s ability.
Outputfor each Test,output the number of groups.
Sample Input
24 23 1 2 410 50 3 4 5 2 1 6 7 8 9
Sample Output
528Hint
Source2015 multi-university Training Contest 1
Recommendwe carefully selected several similar problems for you:5299 5298 5297 5296 5295
/* ***********************************************author:ckbosscreated time:2015 July 21 Tuesday 12:36 35 seconds file Name : 1002.cpp************************************************ * * #include <iostream> #include <cstdio># Include <cstring> #include <algorithm> #include <string> #include <cmath> #include <cstdlib > #include <vector> #include <queue> #include <set> #include <map>using namespace Std;typedef Long long int ll;const int maxn=100100;struct node{int val,pos;}; int N,k;int a[maxn];//Q1 dizheng Q2 dijiandeque<node> Q1,Q2; LL Ans;int Main () {//freopen ("In.txt", "R", stdin); Freopen ("OUT.txt", "w", stdout); int t_t; scanf ("%d", &t_t); while (t_t--) {ans=0; while (!q1.empty ()) Q1.pop_back (); while (!q2.empty ()) Q2.pop_back (); scanf ("%d%d", &n,&k); for (int i=0;i<n;i++) scanf ("%d", a+i); int head=0; for (int i=0;i<n;i++) {NoDe node = (node) {a[i],i}; Push Q1 tail Dizheng while (!q1.empty ()) {Node b = q1.back (); if (b.val<node.val) Q1.pop_back (); else break; } q1.push_back (node); Push Q2 tail Dijian while (!q2.empty ()) {Node b = q2.back (); if (b.val>node.val) Q2.pop_back (); else break; } q2.push_back (node); if (i==0) ans++; else {//Bijiao head while (true) {Node big = Q1.front (); Node small = Q2.front (); if (big.val-small.val<k) break; else {if (Small.pos<big.pos) { head=small.pos+1; Q2.pop_front (); } else {head=big.pos+1; Q1.pop_front (); }}} ans+=i-head+1; }} cout<<ans<<endl; } return 0;}
Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.
Hdoj 5289 Assignment Monotone queue