HDU 5289 Assignment (尺取+Set)

題意:n個數字中取出連續的一組數字使得任意兩個差小於k,求方案數。

解析:two points,用multiset維護一下區間差值即可。

[code]:

#include<cstdio>
#include<cstring>
#include<set>

using namespace std;
typedef long long LL;
const int maxn = 1e5+5;

int n,m;
LL a[maxn];
multiset<LL> ms;
multiset<LL>::iterator it;

void init(){
    ms.clear();
}

void add(LL x){
    ms.insert(x);
}
void del(LL x){
    ms.erase(ms.find(x));
}
bool ok(){
    LL val;
    if(ms.size()<2) return true;
    it = ms.end();
    --it;
    return *it-*ms.begin()<m;
}

int main(){
    int i,j,cas;
    scanf("%d",&cas);
    while(cas--){
        scanf("%d%d",&n,&m);
        init();
        for(i = 1;i <= n;i++) scanf("%lld",&a[i]);
        LL ans=  0;
        for(i = j = 1;i <= n;i++){
            for(;j <= n;j++){
                add(a[j]);
                if(!ok()){
                    del(a[j]);
                    break;
                }
            }
//printf("%d %d\n",i,j);
            ans += ms.size();
            del(a[i]);
        }
        printf("%lld\n",ans);
    }

    return 0;
}



發佈了219 篇原創文章 · 獲贊 4 · 訪問量 5萬+
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章