OJ-Problems-Source/.ACM-Templates/TXTs/莫队.txt

29 lines
1.2 KiB
Plaintext
Raw Normal View History

2016-11-22 09:38:35 +08:00
//Ī<><C4AA><EFBFBD>㷨 O(n^1.5)
//Ī<><C4AA><EFBFBD><EFBFBD><E3B7A8><EFBFBD><EFBFBD><EFBFBD>ߴ<EFBFBD><DFB4><EFBFBD>һ<EFBFBD><D2BB><EFBFBD><EFBFBD><EFBFBD><EFBFBD>޸IJ<DEB8>ѯ<EFBFBD><D1AF><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>
//<2F><><EFBFBD><EFBFBD><EFBFBD><EFBFBD>֪<EFBFBD><D6AA><EFBFBD><EFBFBD>[L,R]<5D>Ĵ<EFBFBD><C4B4><EFBFBD>, <20><><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD><EFBFBD>O(1)<29><>ʱ<EFBFBD><CAB1><EFBFBD>µõ<C2B5>[L,R-1]<5D><>[L,R+1]<5D><>[L-1,R]<5D><>[L+1,R]<5D>Ĵ𰸵Ļ<F0B0B8B5>, <20>Ϳ<EFBFBD><CDBF><EFBFBD>ʹ<EFBFBD><CAB9>Ī<EFBFBD><C4AA><EFBFBD>
//lydsy 2038: [2009<30><39><EFBFBD>Ҽ<EFBFBD>ѵ<EFBFBD><D1B5>]СZ<D0A1><5A><EFBFBD><EFBFBD><EFBFBD><EFBFBD>(hose)
int n, m;
int c[N], pos[N];
int ansup[N], ansdn[N], cnt[N];
struct Node {
int l, r, id;
bool operator<(const Node &b)const { return pos[l] < pos[b.l] || (pos[l] == pos[b.l] && r < b.r); }
} q[N];
int main() {
while (~scanf("%d%d", &n, &m)) {
memset(cnt, 0, sizeof(cnt)); ll ans = 0;
for (int i = 1, nn = ceil(sqrt(n)); i <= n; i++) { scanf("%d", &c[i]); pos[i] = (i - 1) / nn; }
for (int i = 0; i < m; i++) { scanf("%d%d", &q[i].l, &q[i].r); q[i].id = i; }
sort(q, q + m);
for (int i = 0, l = 1, r = 0; i < m; i++) {
for (; l > q[i].l;) { ans += cnt[c[--l]]++; }
for (; l < q[i].l;) { ans -= --cnt[c[l++]]; }
for (; r < q[i].r;) { ans += cnt[c[++r]]++; }
for (; r > q[i].r;) { ans -= --cnt[c[r--]]; }
ll dn = (r - l + 1LL) * (r - l) >> 1, gcd = __gcd(ans, dn);
ansup[q[i].id] = ans / gcd; ansdn[q[i].id] = dn / gcd;
}
for (int i = 0; i < m; i++) { printf("%d/%d\n", ansup[i], ansdn[i]); }
}
}