P4135 作诗
P4135 作詩
題意:
給定 n 個不大于 c 的正整數 a1…an 和 m 組詢問,每次問 [l,r] 中有多少個數出現正偶數次。
對于每次詢問:
設上一個詢問的答案為 ans(第一個詢問時 ans=0),令L=(l+ans)mod n+1,R=(r+ans)mod n+1,若L>R,交換 L 和 R,則本次詢問為[L,R]。
題解:
第一反應是莫隊,但是題目明確說了是強制在線
當這種區間問題想不到什么好方法時,分塊暴力就是最好的方法
首先預處理前i塊內顏色為j的出現幾次sum[i][j]
ans[i][j]表示第i塊到第j塊內有多少數出現了偶數次
cnt[i]表示i顏色出現次數(cnt每次用完都會清空)
對于每次詢問,我們先求出大塊內的數據以及每個數字出現個數,然后加入左側小塊,更新答案,再加入右側小塊,更新答案
其實就是很暴力很暴力的想法和做法,只是利用分塊優化了復雜度
更新cnt不要用memset,直接for清空就行,不然會超時
時間復雜度 n * sqrt(n)
空間復雜度 n * sqrt(n)
代碼:
這種題真正的寫幾遍才算明白(我寫了三四遍)
#include <bits/stdc++.h> using namespace std; const int MAX_N = 100010; const int MAX_M = 330; int n, m, siz, Ans; int a[MAX_N], belong[MAX_N], cnt[MAX_N], sum[MAX_M][MAX_N], ans[MAX_M][MAX_M];//const int Size = 1 << 16;int read() {int x = 0, f = 1; char ch = getchar();while (!isdigit(ch)) { if (ch == '-') f = -1; ch = getchar(); }while (isdigit(ch)) { x = x * 10 + ch - '0'; ch = getchar(); }return x * f; } int query(int x, int y) {x = (x + Ans) % n + 1, y = (y + Ans) % n + 1;if (x > y) swap(x, y);int l = belong[x], r = belong[y];Ans = 0;if (r <= l + 1)//在一個塊或者相鄰兩個塊內,直接暴力 {for (int i = x; i <= y; ++i){++cnt[a[i]];if (!(cnt[a[i]] & 1)) ++Ans;else if (cnt[a[i]] > 2) --Ans;}for (int i = x; i <= y; ++i) --cnt[a[i]];return Ans;}Ans = ans[l + 1][r - 1];//大塊內有多少數出現了偶數次for (int i = x; i <= l * siz; ++i)//左側小塊 {//加上左側小塊內的數據,看有多少數出現了偶數次 ++cnt[a[i]];if (!((cnt[a[i]] + sum[r - 1][a[i]] - sum[l][a[i]]) & 1)) ++Ans;else if (cnt[a[i]] + sum[r - 1][a[i]] - sum[l][a[i]] > 2) --Ans;}for (int i = (r - 1) * siz + 1; i <= y; ++i)//右側小塊 {//同上 ++cnt[a[i]];if (!((cnt[a[i]] + sum[r - 1][a[i]] - sum[l][a[i]]) & 1)) ++Ans;else if (cnt[a[i]] + sum[r - 1][a[i]] - sum[l][a[i]] > 2) --Ans;}//---清零cnt數組 for (int i = x; i <= l * siz; ++i) --cnt[a[i]];for (int i = (r - 1) * siz + 1; i <= y; ++i) --cnt[a[i]];return Ans; } int main() {n = read(), read(), m = read();for (int i = 1; i <= n; ++i) a[i] = read();siz = sqrt(n) + 1;for (int i = 1; i <= n; ++i){belong[i] = (i - 1) / siz + 1;sum[belong[i]][a[i]]++; }for (int i = 1; i < MAX_N; ++i)for (int j = 1; j <= belong[n]; ++j)sum[j][i] += sum[j - 1][i];//前綴和 //sum[i][a[i]]前i個塊內a[i]出現了幾次 for (int i = 1; i <= belong[n]; ++i)//第i塊內 {int now = 0;for (int j = (i - 1) * siz + 1; j <= n; ++j)//從第i塊到最后內所有數的出現次數 {++cnt[a[j]];if (!(cnt[a[j]] & 1)) ++now;//出現偶數次 else if (cnt[a[j]] > 2) --now;//出現奇數次就撤回 ans[i][belong[j]] = now;//記錄i到j塊內有多少數出現了偶數次 }for (int j = (i - 1) * siz + 1; j <= n; ++j)//清空cnt,不要用memset --cnt[a[j]]; }while (m--){int x = read(), y = read();printf("%d\n", query(x, y));}return 0; }總結
- 上一篇: 《七律·2016》
- 下一篇: P3992 [BJOI2017]开车