• 洛谷P2709 小B的询问


    莫队模版

    本来想能不学莫队就不学,但是这次比赛被莫队卡得好惨,于是学了一发。。

    先切道模板题。。

    最普通的莫队就是把序列分块,然后按照询问所在的块来排序,减少指针的移动次数。。

    #include <bits/stdc++.h>
    #define INF 0x3f3f3f3f
    #define full(a, b) memset(a, b, sizeof a)
    using namespace std;
    typedef long long ll;
    inline int lowbit(int x){ return x & (-x); }
    inline int read(){
        int X = 0, w = 0; char ch = 0;
        while(!isdigit(ch)) { w |= ch == '-'; ch = getchar(); }
        while(isdigit(ch)) X = (X << 3) + (X << 1) + (ch ^ 48), ch = getchar();
        return w ? -X : X;
    }
    inline int gcd(int a, int b){ return b ? gcd(b, a % b) : a; }
    inline int lcm(int a, int b){ return a / gcd(a, b) * b; }
    template<typename T>
    inline T max(T x, T y, T z){ return max(max(x, y), z); }
    template<typename T>
    inline T min(T x, T y, T z){ return min(min(x, y), z); }
    template<typename A, typename B, typename C>
    inline A fpow(A x, B p, C lyd){
        A ans = 1;
        for(; p; p >>= 1, x = 1LL * x * x % lyd)if(p & 1)ans = 1LL * x * ans % lyd;
        return ans;
    }
    const int N = 50005;
    int n, m, k, a[N], cnt[N], ans, res[N];
    struct Query {
        int l, r, id, block;
        bool operator < (const Query &rhs) const {
            return (block ^ rhs.block) ? l < rhs.l : (block & 1) ? r < rhs.r : r > rhs.r;
        }
    }query[N];
    
    void add(int k){
        cnt[a[k]] ++;
        ans += 2 * cnt[a[k]] - 1;
    }
    
    void remove(int k){
        cnt[a[k]] --;
        ans += -2 * cnt[a[k]] - 1;
    }
    
    int main(){
    
        n = read(), m = read(), k = read();
        int t = (int)sqrt(n);
        for(int i = 1; i <= n; i ++) a[i] = read();
        for(int i = 1; i <= m; i ++){
            query[i].l = read(), query[i].r = read();
            query[i].id = i, query[i].block = (query[i].l - 1) / t + 1;
        }
        sort(query + 1, query + m + 1);
        int l = 1, r = 0;
        for(int i = 1; i <= m; i ++){
            int curL = query[i].l, curR = query[i].r;
            while(l < curL) remove(l ++);
            while(r < curR) add(++ r);
            while(l > curL) add(-- l);
            while(r > curR) remove(r --);
            res[query[i].id] = ans;
        }
        for(int i = 1; i <= m; i ++){
            printf("%d
    ", res[i]);
        }
        return 0;
    }
    
  • 相关阅读:
    .Proto 文件转换成.cs文件
    C# 委托和事件
    C# 对word (03、07)的相关操作
    程序中记录日志的封装类
    压缩文件程.ZIP
    xml和对象直接的序列化和反序列化
    C#判断两个日期是否在同一周,某日期是本月的第几周
    vs2008 C# 单元测试
    解压缩.zip文件
    记录一次曲折的维护-重构过程
  • 原文地址:https://www.cnblogs.com/onionQAQ/p/10858207.html
Copyright © 2020-2023  润新知