1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117
| #include <cstdio> #include <cmath> #include <algorithm> using namespace std; typedef long long LL; const int N = 1e5 + 10; int p1[N], p2[N]; int n, m, len, w[N], cnt[N]; LL sum[N], ans[N]; struct Query { int id, l, r, p; bool operator<(const Query &_) const { if (l / len != _.l / len) return l < _.l; return (l / len) & 1 ? r < _.r : r > _.r; } } q[N]; void init(int p) { p1[0] = p2[0] = 1; for (int i = 1; i <= len; i++) p1[i] = (LL)p1[i - 1] * 2 % p; for (int i = 1; i <= len; i++) p2[i] = (LL)p1[len] * p2[i - 1] % p; } int lightpow(int k, int p) { return (LL)p1[k % len] * p2[k / len] % p; } namespace Chain { int tl, pre[N], nxt[N]; void insert(int x) { pre[x] = tl; nxt[tl] = x; tl = x; } void remove(int x) { if (x == tl) { nxt[pre[x]] = 0; tl = pre[x]; } else { nxt[pre[x]] = nxt[x]; pre[nxt[x]] = pre[x]; } pre[x] = nxt[x] = 0; } LL query(int k, int p) { LL res = 0; for (int i = tl; i; i = pre[i]) res = (res + (LL)sum[i] * (lightpow(k, p) - lightpow(k - i, p)) % p + p) % p; return res; } } void add(int x) { if (cnt[x]) { sum[cnt[x]] -= x; if (!sum[cnt[x]]) Chain::remove(cnt[x]); } cnt[x]++; if (!sum[cnt[x]]) Chain::insert(cnt[x]); sum[cnt[x]] += x; } void remove(int x) { sum[cnt[x]] -= x; if (!sum[cnt[x]]) Chain::remove(cnt[x]); cnt[x]--; if (cnt[x]) { if (!sum[cnt[x]]) Chain::insert(cnt[x]); sum[cnt[x]] += x; } } int main() { scanf("%d%d", &n, &m); len = sqrt(n) + 1; for (int i = 1; i <= n; i++) scanf("%d", &w[i]); for (int i = 1; i <= m; i++) { q[i].id = i; scanf("%d%d%d", &q[i].l, &q[i].r, &q[i].p); } sort(q + 1, q + m + 1); for (int i = 1, l = 1, r = 0; i <= m; i++) { while (l > q[i].l) add(w[--l]); while (r < q[i].r) add(w[++r]); while (l < q[i].l) remove(w[l++]); while (r > q[i].r) remove(w[r--]); init(q[i].p); ans[q[i].id] = Chain::query(q[i].r - q[i].l + 1, q[i].p); } for (int i = 1; i <= m; i++) printf("%lld\n", ans[i]); return 0; }
|