BZOJ2038 2009国家集训队 小Z的袜子(hose) 题解&代码

莫队原例题【有气无力状】…手推那个O(1)的转移计算就行辣…
一眼看过去和上一道题差别不大…懒得写其它解释了
莫队详解参见上一题http://blog.csdn.net/rainbow6174/article/details/50858386
——————————分割线————————————
发出来之后代码格式错了orz心塞

/**************************************************************
    Problem: 2038
    User: Rainbow6174
    Language: C++
    Result: Accepted
    Time:1076 ms
    Memory:3048 kb
****************************************************************/

#include 
#include 
#include 
#include 
#define LL long long
using namespace std;
const int maxn = 50005;
int n, m, k, l, r, c[maxn], p[maxn], le[maxn], ri[maxn], len[maxn];
LL temp, ans[maxn], cnt[maxn], temp2;
bool cmp(int a,int b)
{
    if(len[a] == len[b]) return ri[a] < ri[b];
    return len[a] < len[b];
}
LL gcd(LL a, LL b)
{
    if(!b)return a;
    return gcd(b, a%b);
}
int main(void)
{
    scanf("%d%d",&n, &m);
    k = sqrt(n);
    for(int i = 1; i <= n; i++)
        scanf("%d", &c[i]);
    for(int i = 0; i < m; i++)
    {
        scanf("%d%d", &le[i], &ri[i]);
        p[i] = i;
        len[i] = (le[i]-1)/k+1;
    }
    sort(p, p+m, cmp);
    l = 1;
    for(int i = 0; i < m; i++)
    {
        while(l < le[p[i]]) cnt[c[l]]--, temp -= cnt[c[l]], l++;
        while(l > le[p[i]]) temp += cnt[c[--l]], cnt[c[l]]++;
        while(r < ri[p[i]]) temp += cnt[c[++r]], cnt[c[r]]++;
        while(r > ri[p[i]]) cnt[c[r]]--, temp -= cnt[c[r]], r--;
        ans[p[i]] = temp;
    }
    for(int i = 0; i < m; i++)
    {
        if(!ans[i]) printf("0/1\n");
        else temp2 = ((LL)(ri[i]-le[i]+1)*(LL)(ri[i]-le[i]))/2,
            temp = gcd(ans[i], temp2),
            printf("%lld/%lld\n",ans[i]/temp, temp2/temp);
    }
    return 0;
}

你可能感兴趣的:(BZOJ,莫队,BZOJ学习记录)