莫队模版
本来想能不学莫队就不学,但是这次比赛被莫队卡得好惨,于是学了一发。。
先切道模板题。。
最普通的莫队就是把序列分块,然后按照询问所在的块来排序,减少指针的移动次数。。
#include#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 inline T max(T x, T y, T z){ return max(max(x, y), z); }template inline T min(T x, T y, T z){ return min(min(x, y), z); }template 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\n", res[i]); } return 0;}