2015 Multi-University Training Contest 1 - 1002 Assignment

本文提供了一种使用两个优先队列来维护区间最大值和最小值的方法,以解决HDU 5289题目中关于连续区间极值差的问题。该方法的时间复杂度为O(N),并在ACM题解中得到了验证。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 Assignment

Problem's Link:  http://acm.hdu.edu.cn/showproblem.php?pid=5289


 

Mean: 

给你一个数列和一个k,求连续区间的极值之差小于k的数的个数。

analyse:

用两个优先队列来维护区间的最大值和最小值,每次插入新值的时候检查区间内的极值差是否满足条件,不满足就将最左边的数删除,直到满足条件为止。ans每次加上区间的长度即得最终答案。

Time complexity: O(N)

 

Source code: 

/*
* this code is made by crazyacking
* Verdict: Accepted
* Submission Date: 2015-07-21-21.38
* Time: 0MS
* Memory: 137KB
*/
#include <queue>
#include <cstdio>
#include <set>
#include <string>
#include <stack>
#include <cmath>
#include <climits>
#include <map>
#include <cstdlib>
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstring>
#define  LL long long
#define  ULL unsigned long long
using namespace std;

int main()
{
      ios_base::sync_with_stdio( false );
      cin.tie( 0 );
      int Cas;
      cin >> Cas;
      while( Cas-- )
      {
            int n, k, tmp;
            cin >> n >> k;
            vector<int> v;
            for( int i = 0; i < n; ++i )
            {
                  cin >> tmp;
                  v.push_back( tmp );
            }
            multiset<pair<int, int> > q1, q2;
            int l = 0, r = 0;
            LL ans = 0;
            while( r < n )
            {
                  q1.insert( make_pair( v[r], r ) ), q2.insert( make_pair( -v[r], r ) );
                  while( -( *q1.begin() ).first - ( *q2.begin() ).first >= k )
                  {
                        q1.erase( make_pair( v[l] , l ) ), q2.erase( make_pair( -v[l], l ) );
                        l++;
                  }
                  ans += r - l + 1;
                  r++;
            }
            cout << ans << endl;
      }
      return 0;
}
/*

*/

  

转载于:https://www.cnblogs.com/crazyacking/p/4667357.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值