hdu5213 莫隊算法

題目鏈接

hdu5213

解法

把一次查詢通過容斥拆分成四個查詢,用一個數組記錄不同數字出現個數,本以爲是我更新順序寫挫,其實是1和2打竄了。。。 樣例依然是對的,我服了,怎麼寫樣例永遠對。。

#include<cstdio>
#include<algorithm>
#include<cstring>

using namespace std;

const int SIZE = 30005;
const int QSIZE = SIZE * 4;
const int BLOCK = 346;

int a[SIZE], res[SIZE];
int N, K, cnt[SIZE], M, ans;

struct node {
    int L, R, i, add;
    void _(int _l, int _r, int _i, int _a){
        L = _l; R = _r; i = _i; add = _a;
    }
} q[QSIZE];

bool cmp(const node &x, const node &y) {
    if(x.L/BLOCK != y.L/BLOCK) return x.L/BLOCK < y.L/BLOCK;
    return x.R < y.R;
}

void add(int pos) {
    if(K - a[pos] > 0 && K - a[pos] <= N) ans += cnt[K - a[pos]];
    cnt[a[pos]]++;//雖然順序很重要但是這個題裏面貌似K是奇數所以無所謂?
}

void remove(int pos) {
    cnt[a[pos]]--;
    if(K - a[pos] > 0 && K - a[pos] <= N) ans -= cnt[K - a[pos]];
}

int main() {
    while(~scanf("%d%d",&N,&K)) {  
        for(int i = 1; i <= N; i++) scanf("%d",&a[i]);
        int Q;
        ans = 0;
        memset(cnt, 0, sizeof(cnt));
        memset(res, 0, sizeof(res));
        scanf("%d",&Q);
        for(int i = 0; i < Q; i++) {
            int l1, r1, l2, r2;
            scanf("%d%d%d%d",&l1,&r1,&l2,&r2);
            q[i*4]._(l1, r2, i, 1);
            q[i*4 + 1]._(l1, l2 - 1, i, -1);
            q[i*4 + 2]._(r1 + 1, r2, i, -1);
            q[i*4 + 3]._(r1 + 1, l2 - 1, i, 1); 
            //注意別把12打躥。。。。
        }
        M = 4 * Q;
        sort(q, q + M, cmp);
        int l = 1, r = 1; //已計算部分l...r-1
        for(int i = 0; i < M; i++) {
            int L = q[i].L, R = q[i].R, addn = q[i].add;
            //if(L > R) continue;
            while(l < L) remove(l++);
            while(r > R+1) remove((r--) - 1); 
            while(l > L) add((l--) - 1);
            while(r <= R) add(r++);
            res[q[i].i] += ans * addn;
        }
        for(int i = 0; i < Q; i++) printf("%d\n",res[i]);
    }
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章