HYSBZ - 2038 小Z的袜子(hose)(莫队算法)

题目链接:https://www.lydsy.com/JudgeOnline/problem.php?id=2038

思路:直接莫队,模板题,注意longlong

代码:

#include <bits/stdc++.h>
#define INF 0x3f3f3f3f
#define eps 1e-8
#define fuck(x) cout<<"<"<<x<<">"<<endl
#define lson l, m, rt<<1
#define rson m+1, r, rt<<1|1
using namespace std;
typedef long long LL;
typedef pair<int, int> pii;
const int maxn = 5e4 + 5;
const int mod = 1e9 + 7;

int n, m;
int a[maxn],pos[maxn];
LL ansx[maxn],ansy[maxn];
LL sum;
LL num[maxn];
struct query {
    int l, r, id;
} q[200005];
bool cmp(query a,query b){
    return pos[a.l]==pos[b.l]?a.r<b.r:pos[a.l]<pos[b.l];
}
LL gcd(LL a,LL b){
    return b?gcd(b,a%b):a;
}
void add(int pos) {
    sum-=num[a[pos]]*num[a[pos]];
    num[a[pos]]++;
    sum+=num[a[pos]]*num[a[pos]];
}
void reduce(int pos) {
    sum-=num[a[pos]]*num[a[pos]];
    num[a[pos]]--;
    sum+=num[a[pos]]*num[a[pos]];
}
int main() {
    scanf("%d%d",&n,&m);
    for (int i=1;i<=n;i++) scanf("%d",&a[i]);
    int block=int(sqrt(n));
    for (int i=1;i<=n;i++) pos[i]=(i-1)/block+1;
    for (int i=1;i<=m;i++){
        scanf ("%d%d",&q[i].l,&q[i].r);
        q[i].id=i;
    }
    sort(q+1,q+1+m,cmp);
    int l=1,r=0;
    sum=0;
    for (int i=1;i<=m;i++){
        int id=q[i].id;
        while (r<q[i].r) add(++r);
        while (r>q[i].r) reduce(r--);
        while (l>q[i].l) add(--l);
        while (l<q[i].l) reduce(l++);
        ansx[id]=sum-(q[i].r-q[i].l+1);
        ansy[id]=(LL)(q[i].r-q[i].l+1)*(q[i].r-q[i].l);
        if (ansx[id]==0) {
            ansy[id]=1;
            continue;
        }
        LL tmp=gcd(ansx[id],ansy[id]);
        ansx[id]=ansx[id]/tmp;
        ansy[id]=ansy[id]/tmp;
    }
    for (int i=1;i<=m;i++){
        printf ("%lld/%lld\n",ansx[i],ansy[i]);
    }
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值