标签:
[BZOJ2038][2009国家集训队]小Z的袜子(hose)
试题描述
输入
输出
输入示例
6 4 1 2 3 3 3 2 2 6 1 3 3 5 1 6
输出示例
2/5 0/1 1/1 4/15
数据规模及约定
30%的数据中 N,M ≤ 5000;
60%的数据中 N,M ≤ 25000;
100%的数据中 N,M ≤ 50000,1 ≤ L < R ≤ N,Ci ≤ N。
题解
注意到 Ci ≤ N,于是可以记录每个颜色个数,从而使答案计算起来非常简便。进一步发现:当我们知道区间 [l, r] 的答案时,可以很容易地得出 [l + 1, r], [l - 1, r], [l, r - 1], [l, r + 1] 这些区间的答案,于是就可以用莫队搞了。
#include <iostream> #include <cstdio> #include <algorithm> #include <cmath> #include <stack> #include <vector> #include <queue> #include <cstring> #include <string> #include <map> #include <set> using namespace std; const int BufferSize = 1 << 16; char buffer[BufferSize], *Head, *Tail; inline char Getchar() { if(Head == Tail) { int l = fread(buffer, 1, BufferSize, stdin); Tail = (Head = buffer) + l; } return *Head++; } int read() { int x = 0, f = 1; char c = Getchar(); while(!isdigit(c)){ if(c == ‘-‘) f = -1; c = Getchar(); } while(isdigit(c)){ x = x * 10 + c - ‘0‘; c = Getchar(); } return x * f; } #define maxn 50010 #define LL long long int n, m, col[maxn], has[maxn]; LL Ans[maxn], Bns[maxn]; struct Que { int id, l, r; } qs[maxn], tq[maxn]; bool cmpl(Que a, Que b) { return a.l < b.l; } bool cmpr(Que a, Que b) { return a.r < b.r; } LL gcd(LL a, LL b) { return !b ? a : gcd(b, a % b); } int main() { n = read(); m = read(); for(int i = 1; i <= n; i++) col[i] = read(); for(int i = 1; i <= m; i++) qs[i].id = i, qs[i].l = read(), qs[i].r = read(); sort(qs + 1, qs + m + 1, cmpl); // for(int i = 1; i <= m; i++) printf("%d %d %d\n", qs[i].id, qs[i].l, qs[i].r); int mxl = qs[m].l, siz = (int)sqrt(mxl + .5), nl = 1, nr = siz; for(int i = 1; i <= m;) { int j, k, x; for(j = i; j < m && nl <= qs[j].l && qs[j].l <= nr; j++) ; // for(x = i; x <= j; x++) printf("here: %d %d %d\n", qs[x].l, qs[x].r, qs[x].id); sort(qs + i, qs + j + 1, cmpr); i = j + 1; nl = nr + 1; nr = nl + siz - 1; } // for(int i = 1; i <= m; i++) printf("%d %d %d\n", qs[i].id, qs[i].l, qs[i].r); nl = 1, nr = 0; LL ans = 0; // has[col[1]] = 1; for(int i = 1; i <= m; i++) { int ql = qs[i].l, qr = qs[i].r; while(qr > nr) nr++, ans += has[col[nr]], has[col[nr]]++; while(ql < nl) nl--, ans += has[col[nl]], has[col[nl]]++; while(qr < nr) has[col[nr]]--, ans -= has[col[nr]], nr--; while(ql > nl) has[col[nl]]--, ans -= has[col[nl]], nl++; int len = qr - ql + 1; Ans[qs[i].id] = ans; Bns[qs[i].id] = (LL)len * (LL)(len - 1) >> 1ll; // printf("%d %d %d %lld %d\n", qs[i].id, ql, qr, ans, len); } for(int i = 1; i <= m; i++) { LL a = Ans[i], b = Bns[i], g; if(!a){ puts("0/1"); continue; } g = gcd(a, b); a /= g; b /= g; printf("%lld/%lld\n", a, b); } return 0; }
[BZOJ2038][2009国家集训队]小Z的袜子(hose)
标签:
原文地址:http://www.cnblogs.com/xiao-ju-ruo-xjr/p/5760397.html