J: A Simple Problem

Description
在一个由N个整数组成的数列中,最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K呢?
Input
输入包含若干组数据。每组数据的第一行有2个正整数,N(1<=N<=10^6),K(0<=K<=10^6),其中N、K的含义同上,接下来一行一共有N个32位有符号整数(32-bit signed integer),依次描绘了这个数列中各个整数的值。
Output
对于每组数据,输出一个正整数,表示在这个数列中最多能找到多少个位置连续的整数且其中的最大值与最小值之差不超过K。
Sample Input
4 2
3 1 5 2

3 2
3 1 2
Sample Output
2
3


首先,排除暴力。然后想到了在扫描的时候发现不max-min>k时,
取下标为min(maxindex,minindex)+1。但是这样在下标之后的值还是会重新扫描,最坏情况就是递增序列。几乎跟暴力一样。
最后的解为:2个指针,当序列满足要求的时候right右移。反之,left右移。
其之间的序列放在一个multiset中维护。right右移,插入元素。left右移删除元素。注意left右移后要用迭代器删除,否则会删除所有与之相等的值(是最大最小值就会造成影响)。

#include <iostream>
#include <cstdio>
#include <cstring>
#include <vector>
#include <cmath>
#include <algorithm>
#include <string>
#include <set>
#include <map>
#define MIN(a,b) ((a)<(b)?(a):(b))
#define MAX(a,b) ((a)>(b)?(a):(b))
using namespace std;

char s[10], c[10];
long long int A[1000005];
int main()
{
    long long int x, y;
    long long int max = 0, min = 999999;
    multiset<long long int>ss;

    while (scanf_s("%lld%lld", &x, &y) != EOF) {
        for (long long int i = 0; i < x; i++) {
            scanf_s("%lld", &A[i]);
        }
        long long int nlen = 0;
        long long int maxi = 0, mini = 0;
        long long int left = 0, right = 0;
        ss.insert(A[0]);
        while (right!=x) {
            max = *(--ss.end());
            min = *ss.begin();
            if (max - min <= y) {
                nlen = right - left + 1 > nlen ? right - left + 1 : nlen;
                ss.insert(A[++right]);
            }
            else {
                auto pos = ss.find(A[left++]);
                ss.erase(pos);
            }
        }
        cout << nlen << endl;
        ss.clear();
    }
}

猜你喜欢

转载自blog.csdn.net/sc_jn/article/details/80272752
今日推荐