bzoj 2038: [2009国家集训队]小Z的袜子(hose)
1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 inline int read() 5 { 6 int x=0,f=1;char ch=getchar(); 7 while(ch<'0'||ch>'9'){if(ch=='-')f=-1;ch=getchar();} 8 while(ch>='0'&&ch<='9'){x=x*10+ch-'0';ch=getchar();} 9 return x*f; 10 } 11 12 /********************************************************************/ 13 14 const int maxn = 50000+5; 15 int n, m; 16 int a[maxn]; 17 int sz, belong[maxn]; 18 ll ans, num[maxn]; 19 ll up[maxn], dw[maxn]; //分子, 分母 20 21 struct node{ 22 int l, r; 23 int id; 24 }q[maxn]; 25 26 ll gcd(ll x, ll y){ 27 if(y == 0) return x; 28 else gcd(y, x%y); 29 } 30 31 bool cmp(node x, node y){ 32 if(belong[x.l] == belong[y.l]) 33 return x.r < y.r; 34 else 35 return belong[x.l] < belong[y.l]; 36 } 37 38 void update(int x, int d){ 39 ans -= num[a[x]]*num[a[x]]; 40 num[a[x]] += d; 41 ans += num[a[x]]*num[a[x]]; 42 } 43 44 int main(){ 45 n = read(); m =read(); 46 sz = ceil(sqrt(n*1.0)); 47 for(int i = 1;i <= n;i++){ 48 a[i] = read(); 49 belong[i] = (i-1)/sz; 50 } 51 for(int i = 1;i <= m;i++){ 52 q[i].l = read(); q[i].r = read(); 53 q[i].id = i; 54 } 55 sort(q+1, q+1+m, cmp); 56 int pl = 1, pr = 0; 57 ans = 0; 58 for(int i = 1;i <= m;i++){ 59 int id = q[i].id; 60 if(q[i].l == q[i].r){ 61 up[id] = 0; dw[id] = 1; 62 continue; 63 } 64 if(pr < q[i].r){ 65 for(int j = pr + 1;j <= q[i].r;j++){ 66 update(j, 1); 67 } 68 } 69 else{ 70 for(int j = pr;j > q[i].r;j--){ 71 update(j, -1); 72 } 73 } 74 pr = q[i].r; 75 if(pl < q[i].l){ 76 for(int j = pl;j < q[i].l;j++){ 77 update(j, -1); 78 } 79 } 80 else { 81 for(int j = pl - 1;j >= q[i].l;j--){ 82 update(j, 1); 83 } 84 } 85 pl = q[i].l; 86 ll aa = ans - q[i].r + q[i].l - 1; 87 ll bb = 1ll*(q[i].r - q[i].l + 1)*(q[i].r - q[i].l); 88 ll cc = gcd(aa, bb); 89 up[id] = aa/cc; dw[id] = bb/cc; 90 } 91 for(int i = 1;i <= m;i++){ 92 printf("%lld/%lld\n", up[i], dw[i]); 93 } 94 return 0; 95 }