洛谷P3245 [HNOI2016]大数 【莫队】

题目

题解##

除了(5)(2)
后缀数字对(P)取模意义下,两个位置相减如果为(0),那么对应子串即为(P)的倍数
只用对区间种相同数个数(x)贡献({x choose 2})
经典莫队题
(P = 2)(5)就特判一下

#include<iostream>
#include<cstdio>
#include<cmath>
#include<cstring>
#include<algorithm>
#define LL long long int
#define Redge(u) for (int k = h[u],to; k; k = ed[k].nxt)
#define REP(i,n) for (int i = 1; i <= (n); i++)
#define BUG(s,n) for (int i = 1; i <= (n); i++) cout<<s[i]<<' '; puts("");
using namespace std;
const int maxn = 100005,maxm = 100005,INF = 1000000000;
LL n,m,P,B;
char s[maxn];
LL ans[maxn];
struct Que{int l,r,b,id;}q[maxn];
inline bool operator <(const Que& a,const Que& b){
	return a.b == b.b ? a.r < b.r : a.l < b.l;
}
void solve1(){
	scanf("%lld",&m);
	REP(i,m) scanf("%d%d",&q[i].l,&q[i].r),q[i].id = i,q[i].b = q[i].l / B;
	sort(q + 1,q + 1 + m);
	LL L = q[1].l,R = q[1].r; LL cnt = 0,sum = 0;
	for (int i = L; i <= R; i++){
		if ((s[i] - '0') % P == 0) cnt++,sum += i - L + 1;
	}
	ans[q[1].id] = sum;
	for (int i = 2; i <= m; i++){
		while (L != q[i].l || R != q[i].r){
			if (L < q[i].l){
				sum -= cnt;
				if ((s[L] - '0') % P == 0) cnt--;
				L++;
			}
			if (L > q[i].l){
				L--;
				if ((s[L] - '0') % P == 0) cnt++;
				sum += cnt;
			}
			if (R < q[i].r){
				R++;
				if ((s[R] - '0') % P == 0) cnt++,sum += R - L + 1;
			}
			if (R > q[i].r){
				if ((s[R] - '0') % P == 0) cnt--,sum -= R - L + 1;
				R--;
			}
		}
		ans[q[i].id] = sum;
	}
	REP(i,m) printf("%lld
",ans[i]);
}
int b[maxn],bi,a[maxn],tot,bac[maxn];
int getn(int x){return lower_bound(b + 1,b + 1 + tot,x) - b;}
LL C(LL x){
	if (x <= 1) return 0;
	return x * (x - 1) / 2;
}
void solve2(){
	for (int i = n,bin = 1; i; i--,bin = bin * 10 % P){
		b[i] = a[i] = ((s[i] - '0') * bin % P + a[i + 1]) % P;
	}
	n++;
	sort(b + 1,b + 1 + n); tot = 1;
	for (int i = 2; i <= n; i++) if (b[i] != b[tot]) b[++tot] = b[i];
	for (int i = 1; i <= n; i++) a[i] = getn(a[i]);
	scanf("%lld",&m);
	REP(i,m){
		scanf("%d%d",&q[i].l,&q[i].r); q[i].r++;
		q[i].id = i,q[i].b = q[i].l / B;
	}
	sort(q + 1,q + 1 + m);
	LL L = q[1].l,R = q[1].r; LL sum = 0;
	for (int i = L; i <= R; i++){
		sum -= C(bac[a[i]]);
		sum += C(++bac[a[i]]);
	}
	ans[q[1].id] = sum;
	for (int i = 2; i <= m; i++){
		while (L != q[i].l || R != q[i].r){
			if (L < q[i].l){
				sum -= C(bac[a[L]]);
				sum += C(--bac[a[L]]);
				L++;
			}
			if (L > q[i].l){
				L--;
				sum -= C(bac[a[L]]);
				sum += C(++bac[a[L]]);
			}
			if (R < q[i].r){
				R++;
				sum -= C(bac[a[R]]);
				sum += C(++bac[a[R]]);
			}
			if (R > q[i].r){
				sum -= C(bac[a[R]]);
				sum += C(--bac[a[R]]);
				R--;
			}
		}
		ans[q[i].id] = sum;
	}
	REP(i,m) printf("%lld
",ans[i]);
}
int main(){
	scanf("%lld%s",&P,s + 1);
	n = strlen(s + 1); B = (int)sqrt(n) + 1;
	if (P == 2 || P == 5) solve1();
	else solve2();
	return 0;
}

原文地址:https://www.cnblogs.com/Mychael/p/8986650.html